0
StringTemplate insert = new StringTemplate("insert $table$ values($value;separator=\",\"$)");
int testSize = 10000;
for(int i=0;i<testSize;i++) {           
    insert.setAttribute("table", "aTable");
    String[] vs = {"1", "1", "'aaa'", "'bbb'"};
    for(int j = 0;j < vs.length;j++){   
        insert.setAttribute("value", vs[j]);    
    }
    insert.toString();  
    insert.reset(); 
}   

Above would slower than following plain StringBuilder roughly by 5 times....

int testSize = 10000;
StringBuilder sb= new StringBuilder(100);
for(int i=0; i<testSize; i++) {
    sb.append("INSERT ").append("aTable (");
    String[] v = {"1", "1", "'aaa'", "'bbb'"};
    for(int j=0; j<v.length; j++) { 
        if(j > 0) {
        sb.append(",");
        }
        sb.append(v[j]);    
    }
    sb.append(")");
    sb.toString();
}

Any idea or suggestions about how to improve StringTemplate's efficiency? Thanks! StringTemplate seems to invoke toString() on each token, right?

reevesy
  • 3,452
  • 1
  • 26
  • 23
rayeaster
  • 261
  • 4
  • 16
  • 1
    You need to describe the question better. Are you expecting us to execute the code, time it, and come up with the data to tell us what your question really is? Instead, tell us what you see from those tests, what you expected, and possibly your hypothesis about the reason for the difference. – Lasse V. Karlsen Apr 28 '11 at 10:06
  • 1
    For instance, let's start with, which language/runtime is this? What is StringTemplate (since you don't have it in the code at all.) When you say "any idea or suggestions?", then my question is "about what?" Basically... **what is your question**? – Lasse V. Karlsen Apr 28 '11 at 10:07
  • @ Lasse V. Karlsen: you're perfectly right.I raise my question more clearly now. – rayeaster Apr 28 '11 at 11:51

2 Answers2

6

I don't think you can draw valid performance conclusions from such a small test; how does it perform in real world usage?

Under the hood StringTemplate has to do a lot more work than just naïvely using a StringBuilder like you have done (it needs to construct abstract syntax trees, walk them, render text, etc), which probably contributes to the overhead. You haven't mentioned anything about what version of StringTemplate you're using; supposedly StringTemplate 4 is much faster than previous versions, partially because it involves direct translation to bytecode.

In general there will be a tradeoff between performance and maintainability, readability, and reuse. If StringTemplate is fast enough for your purposes, I think its benefits far outweigh its problems.

I82Much
  • 26,901
  • 13
  • 88
  • 119
1

Use ST in StringTemplate4 rather than StringTemplate in anltr3.3

rayeaster
  • 261
  • 4
  • 16