Question

I came across two code snippets which were creating a query to be executed further:

StringBuilder stringBuilder = new StringBuilder(); 
stringBuilder.append("SELECT * FROM EMPLOYEE "); 
stringBuilder.append("WHERE SALARY > ? "); 
stringBuilder.append("GROUP BY DEPT");

And

String string = "SELECT * FROM EMPLOYEE " +
"WHERE SALARY > ? " +
"GROUP BY DEPT";

According to my analysis, both the snippets create 4 objects. First snippet creates a StringBuilder object and 3 string objects while the second snippet creates 4 String objects. Is my analysis correct?

How snippet one is more efficient than snippet 2?

Was it helpful?

Solution

Your first analysis is correct, but second snippet creates only one String Object. Because, it's a compile time concatenation of Strings literals.

OTHER TIPS

Not exactly...

The first version creates 1 StringBuilderevery execution and 3 String constants (created/interned once per JVM start). It will create another String object every execution when you go to use the value via stringBuilder.toString().

The second creates 1 String constant (created/interned once per JVM start) because the value of the entire concatenation is known at compile time. It is equivalent in effect to:

String string = "SELECT * FROM EMPLOYEE WHERE SALARY > ? GROUP BY DEPT";

The StringBuilder example will create 4 objects.

Whereas the second example will just create one String object. Even though you have concatenated 3 String literals, model Java compilers are smart enough to detect that you have concatenated static String literals and thus will append all of them into one and create a single String object.

Therefore,

String string = "SELECT * FROM EMPLOYEE " +
"WHERE SALARY > ? " +
"GROUP BY DEPT";

is same as

String string = "SELECT * FROM EMPLOYEE WHERE SALARY > ? GROUP BY DEPT";

Strings are immutable so each time you do a concatenation (. operator) you're creating a new String object in memory. With StringBuilder you're adding the text to the same object so a new ones do not need to be created.

The first snippet create 1 object. It's concatenate in compile-time.

StringBuilder has better performance when you are concatenating mutable strings. For example, with your example:

StringBuilder stringBuilder = new StringBuilder(); 
stringBuilder.append("SELECT * FROM EMPLOYEE "); 
if(salary > 0) {
    stringBuilder.append("WHERE SALARY > ? "); 
}
if(group == true) {
    stringBuilder.append("GROUP BY DEPT");
}

String string = "SELECT * FROM EMPLOYEE ";
if(salary > 0) {
    string = string + "WHERE SALARY > ? ";
}
if(group == true) {
    string = = string + "GROUP BY DEPT";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top