1

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.

2
  • 3
    there is also query.append(" t.field = ").append(object.field); Commented Jul 7, 2013 at 16:33
  • StringBuilder seems an overkill in this particular case. Commented Jul 7, 2013 at 16:35

3 Answers 3

6

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 ); 
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.