CyberiaPC.com Community Forums Main Page
RSS Feeds: Late(st) News | Zenith Picture Gallery | Most Recent Community Topics | Tips, Tricks and Other Useful Stuff

Welcome Guest ( Log In | Register )

Reply to this topicStart new topic
> Is StringBuffer faster than the '+' operator? [Java]
usr.c
post Apr 2 2009, 09:16 AM
Post #1


Boss, my code's compiling (xkcd)
Group Icon

Group: Admins
Posts: 10,440
Joined: 19-September 01
Member No.: 1

Nothing Selected




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
Go to the top of the page
 
+Quote Post
MaD_cOw
post Apr 2 2009, 06:35 PM
Post #2


No way... It compiles? SHIP IT!
Group Icon

Group: Moderators
Posts: 609
Joined: 27-December 04
From: Thunder Bay, Ontario Canada
Member No.: 2,133

Canada




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
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



RSS Lo-Fi Version Time is now: 24th May 2013 - 04:48 AM