+ 6

Advice

advice to beginners: if your program is running really slow, try replacing all the strings with a StringBuilder. e.g. String s = "hello"; instead of doing s += " world"; replaced with: StringBuilder sb = new StringBuilder ("hello"); sb.append (" world"); String final = sb.toString(); ok reason why += string is slow is because everytime you do that, java implicitly creates a new String object. with StringBuilder, there is only one object created, so there are not a bunch of objects to garbage collect

22nd Apr 2017, 6:15 AM
Edward
6 odpowiedzi
+ 6
I never wrote code in Java, but can this really make that much of an perfomance impact? :o
22nd Apr 2017, 6:17 AM
Tim G
Tim G - avatar
+ 6
Advice part 2 lol i ran out of space. anyway i just wanted to share my experience with the stringbuilder. i was trying to run a loop 10000 times. inside the loop i had a bunch of string += "stuff"; it wouldnt even finish compiling cause of how slow it was running. then i switched to stringbuilder and instead now i can run the program even with 1000000 iterations, and it seems almost instant so this is why i suggest everyone switching to StringBuilder (at least for java. not sure how other languages work) so yes. it really can make that much of a performance difference
22nd Apr 2017, 6:19 AM
Edward
+ 3
yup @andre. i was doing like 5 concatenations per iteration. so in total it was like 50000 new object creations but obviously if you are only going to concatenate like 5 times, then you wont see much performance increase in using stringbuilder
22nd Apr 2017, 6:34 AM
Edward
+ 1
@Tim G. Yes, because like Edward said, += creates a new string object. Meaning that a new reference to that object is created in memory. If you do this a lot it can be very slow since the memory is being filled with references to objects.
22nd Apr 2017, 1:15 PM
José Pereira
José Pereira - avatar
- 1
Ehm... Can you not use reserved keywords like final as modifiers?
22nd Apr 2017, 9:39 AM
Alex Snaidars
Alex Snaidars - avatar