Reputation: 14456
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.
Upvotes: 1
Views: 2552
Reputation: 6507
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), or
Use an explicit StringBuilder
with a call to append
for each little piece of the string you are building (don't use +
anywhere).
Upvotes: 2
Reputation: 11209
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.
Upvotes: 1
Reputation: 10696
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 );
}
Upvotes: 6