Wondering what is the best way to use it:
StringBuilder query = new StringBuilder(" Select * from mytable t where ");
for ( Object object : objects ) {
query.append(" t.field = " + object.field ); // this one OR
query.append( object.field ); // this one?
}
Not sure which one is recommended to use.
3 Answers 3
String builder is much faster, so it's not recommended doing concatenations of more than say 3-4 strings (outside of a loop), and definitely not in loops, I'd suggest you do like this:
for ( Object object : objects ) {
query.append(" t.field = ");
query.append( object.field );
}
Two separate calls to append
are better. Behind the scenes, the use of +
on strings results in a StringBuilder
being created to do the concatenation. So, you want to either:
Concatenate all your strings in one shot using
+
(which doesn't work in your dynamic case), orUse an explicit
StringBuilder
with a call toappend
for each little piece of the string you are building (don't use+
anywhere).
Use append. However, note that if you are doing relatively few loops (say 10 - 20), then it does not really matter if you use StringBuilder and you may not see any performance improvement.
Explore related questions
See similar questions with these tags.
query.append(" t.field = ").append(object.field);