![]() ![]() |
Apr 2 2009, 09:16 AM
Post
#1
|
|
![]() Boss, my code's compiling (xkcd) Group: Admins Posts: 10,440 Joined: 19-September 01 Member No.: 1 ![]() |
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), "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 |
|
|
|
Apr 2 2009, 06:35 PM
Post
#2
|
|
|
No way... It compiles? SHIP IT! Group: Moderators Posts: 609 Joined: 27-December 04 From: Thunder Bay, Ontario Canada Member No.: 2,133 ![]() |
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 |
|
|
|
![]() ![]() |
|
Lo-Fi Version | Time is now: 24th May 2013 - 04:48 AM |