• Post Reply Bookmark Topic Watch Topic
  • New Topic

Boolean and String  RSS feed

 
Frederico Zapelini
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code:

boolean x = true;
StringBuffer sb = new StringBuffer(10);
sb.append(x + �abc�);

Does it create 2 objects String (�true� and �trueabc�) and then append trueabc, or it only create 1 object String trueabc? Would be better if I do this?

sb.append(x).append(�abc�);
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Frederico Zapelini:
Does it create 2 objects String (�true� and �trueabc�) and then append trueabc, or it only create 1 object String trueabc? Would be better if I do this?
Neither, and the second code snippet is definitely lots better. The line of codeIs compiled toIn general, concatenation of Strings using the "+" operator will use a temporary StringBuffer object. Appending the strings to your StringBuffer individually will avoid the creation of at least three objects: the StringBuffer, the char[] that it stores the characters in behind the scenes, and the String created by the final toString().

If you really want to know the nitty gritty detail, have a look at the decompiled code:You clearly can see the temporary StringBuffer being created in the first example method.

- Peter
[ June 09, 2004: Message edited by: Peter den Haan ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, let me say that unless you're doing this in a tight loop that will run hundreds of thousands of times, you shouldn't be worrying about it; any difference is exceedingly small.

But in any case, both versions will call String.valueOf(true) to get a String that represents the boolean value; but String.valueOf(true) doesn't create a new String each time it is called -- it just returns one of two constants.

The second version is a very little bit better, though, because the first one adds the two strings together to make a third String object using an intermediate StringBuffer, and then copies this second StringBuffer into the first StringBuffer, while the second doesn't make this third String at all, and only copies the characters from each of the two component Strings in turn.

But as I said, unless this is extremely performance-critical code, you should be worrying about which is clearer and easier to maintain, not which is infinitessimally faster (personally, I like the second one for these reasons, too.)
[ June 09, 2004: Message edited by: Ernest Friedman-Hill ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!