Performance and simplicity tradeoffs between String, StringBuffer, and StringBuilder

后端 未结 5 843
灰色年华
灰色年华 2021-02-09 17:29

Have you ever thought about the implications of this change in the Java Programming Language?

The String class was conceived as an immutable class (and this decision was

5条回答
  •  深忆病人
    2021-02-09 17:39

    StringBuffer was in Java 1.0; it was not any kind of a reaction to slowness or immutability. It's also not in any way faster or better than string concatenation; in fact, the Java compiler compiles

    String s1 = s2 + s3;
    

    into something like

    String s1 = new StringBuilder(s2).append(s3).toString();
    

    If you don't believe me, try it yourself with a disassembler (javap -c, for example.)

    The thing about "StringBuffer is faster than concatenation" refers to repeated concatenation. In that case explicitly creating yoir own StringBuffer and using it repeatedly performs better than letting the compiler create many of them.

    StringBuilder was introduced in Java 5 for performance reasons, as you say. The reason it makes sense is that StringBuffer/Builder are virtually never shared outside of the method that creates them: 99% of their usage is something like the above, where they're created, used to append a few strings together, then discarded.

提交回复
热议问题