Why does StringBuffer have toStringCache while StringBuilder doesn't?

In JDK 8, the class StringBufferhas toStringCache, but StringBuildernot.

/**
 * A cache of the last value returned by toString. Cleared
 * whenever the StringBuffer is modified.
 */
private transient char[] toStringCache;

But why?

  • One of the possible reasons that I can think of is because StringBuffer is already in sync, so the cache might be easier to implement.

  • Or maybe historically StringBuffer was implemented this way, so the old code is highly dependent on this function?

Given the modern JVM with escape analysis and biased blocking, is there more difference?

+6
source share
2 answers

. StringBuilder Java 5, , StringBuffer .

StringBuilder , , . , toString(), ( ?), , , , , - "" "".

StringBuilder , , , String , , StringBuilder s , String StringBuilder , .

, , - ? , , , Java 1.0 StringBuffer. , , .. ...

, Java 1.x , . synchronized - , . , , String.valueOf(char[]) String.copyValueOf(char[]), new String(char[])...

+4

, , StringBuilder , , , StringBuilder .

, new String(...), ; StringBuffer, String(array, boolean), :

, .

+3

All Articles