Jump to content


Photo
- - - - -

Is StringBuffer faster than the '+' operator? [Java]


  • Please log in to reply
1 reply to this topic

#1 usr.c

usr.c

    Boss, my code's compiling (xkcd)

  • Admins
  • 10,440 posts
  • Gender:Male
  • Interests:Software
    Soccer
    Photography
    RC cars
    Electronics

  • Nothing Selected

Posted 02 April 2009 - 09:16 AM

Nope! (read "not necessarily")

There's no point creating a StringBuffer since the '+' operator's implementation already uses it, so code readability would be hindered for no real gain.

If you're using '+=', however, then there will be a difference since Strings in Java are immutable and so every new concatenation would be creating a new String object and tossing away the the old one. Here are the results of a simple test that I did:

QUOTE
Using +
~0s for 100,000 instantiations/concats
~0s for 1,000,000 instantiations/concats

Using StringBuffer
0.1s for 100,000 instantiations/appends
1.1s for 1,000,000 instantiations/appends

Using +=
0.5s for 100,000 instantiations/concats
4.6s for 1,000,000 instantiations/concats

They make me realize two things:
1. Using += within a loop is a bad idea
2. For a pragmatic person trying to refactor a large codebase, there doesn't seem to be much point focusing on micro-benchmarking for small values of n or for concatenations outside of a loop since the difference between any of the above techniques would negligible in such cases.

A small aside: The author of this article reads a bit into the Java Language Spec's section 15.18.1.2, which says: "...a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created..." and points out that the compiler is therefore not obligated to optimize the expression.


Things that I don't suck at: Photography (flickr, JPG Mag), Skydiving, Splitting atoms, Flying a space shuttle
"Don't bail; the best gold is at the bottom of barrels of crap!" -Randy Pausch
I have people-skills goddamnit! What is wrong with you people!!! | www.skyrill.com

#2 MaD_cOw

MaD_cOw

    No way... It compiles? SHIP IT!

  • Moderators
  • 609 posts
  • Location:Thunder Bay, Ontario Canada
  • Interests:Drumming,<br />Music,<br />Mountain Biking,<br />Modding,<br />Vintage Hardware,

  • Canada

Posted 02 April 2009 - 06:35 PM

One of the places I have used "+=" in a loop is making java applet games but other than that is is really a bad idea.


Really interesting read, I have recently given up JAVA for C.

Big change. :|
-Mad_cow




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users