Kevin Rave
Kevin Rave

Reputation: 14456

StringBuilder - Using concatenation vs using append in loop

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

Answers (3)

Rob
Rob

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:

  1. Concatenate all your strings in one shot using + (which doesn't work in your dynamic case), or

  2. 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

Tarik
Tarik

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

Daniel Figueroa
Daniel Figueroa

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

Related Questions