• Post Reply Bookmark Topic Watch Topic
  • New Topic

text += is slow

 
Nikos Stavros
Ranch Hand
Posts: 243
Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
does anyone know why this algorithim is slow. Is it because of the text += code
 
Paul Clapham
Sheriff
Posts: 21862
36
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's possible. It wouldn't take you long to find out, by redeclaring "text" as a StringBuffer (Java 1.4) or StringBuilder (Java 5) and replacing a line of code like this:
 
Scott Johnson
Ranch Hand
Posts: 518
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it's very likely that the string concatenation is impacting performance especially if the strings being concatenated are long and/or there are many of them.

You should avoid using "+" for string concatenation especially in loops. The above solution will be much faster, but you can further improve execution time by eliminating all string concatenation:



Strings are immutable so each time you do concatenation, a new String must be created that is big enough to hold both Strings. StringBuffer and StringBuilder don't need to allocate a new buffer each time something is appended.
 
Nikos Stavros
Ranch Hand
Posts: 243
Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Scot and Paul, your advice very good and helpful. thanks
 
Joe Ess
Bartender
Posts: 9361
11
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Scott Johnson:

You should avoid using "+" for string concatenation especially in loops.

Well, you should use "+" where appropriate. Have a look at this article for a more nuanced view of where to use "+".
I'll bet that using System.out.println() is as big a performance drag as "+" in the above code as it blocks until a call out to the native console returns. Again, this would be an interesting thing to test and measure.
[ August 09, 2006: Message edited by: Joe Ess ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One question would be: slower than what?

This looks pretty small and easy to convert to StringBuilder and in a separate test just remove the system.out call and see what happens. I know I had some thigns that seemed to crawl with displays like that and I changed them to log every 1000 times through or 10k or whatever for much better speed. Let us know what works!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!