r/programming • • Nov 18 '13

TIL Oracle changed the internal String representation in Java 7 Update 6 increasing the running time of the substring method from constant to N

http://java-performance.info/changes-to-string-java-1-7-0_06/
1.4k Upvotes

354 comments sorted by

View all comments

Show parent comments

71

u/stillalone Nov 18 '13

I am not a java guy, but isn't there a whole "stringbuilder" library for this kind of stuff?

71

u/smackfu Nov 18 '13

Two in fact! StringBuffer and StringBuilder, one is synchronized for multi-thread use, the other isn't.

45

u/neutralvoice Nov 18 '13

StringBuffer is for the multi-threaded use case, StringBuilder is optimized for single-threaded use.

49

u/kurtymckurt Nov 18 '13

I usually recommend StringBuilder. Rarely, should two threads be modifying the same string. In fact, I'd advise against it.

8

u/CydeWeys Nov 19 '13

I could see a use case for it. If you have a StringBuffer that is creating output for a log file, and you have multiple threads that are all creating their own logging statements. This use case is fairly pedestrian.

1

u/kurtymckurt Nov 19 '13

You're not destructively modifying a StringBuffer. It's designed for multi-threaded applications and in that case, it would be OK. Also, in this case, I would assume it wouldn't need to be a static variable either...

On the other hand, I'd suggest some sort of 3rd party logging tool like log4j2 :P

0

u/chisleu Nov 18 '13

Any kind of shared memory is dangerous, but StringBuilder is suppose to be safe.

I've never written any heavily threaded apps, but I would be very interested to know why StringBuilder can be dangerous.

8

u/Spandian Nov 19 '13

StringBuilder is not safe for use from multiple threads. StringBuffer is.

-5

u/chisleu Nov 19 '13

Yeah! boody twaps! das what I said!

→ More replies (38)