Performance and simplicity tradeoffs between String, StringBuffer, and StringBuilder

后端 未结 5 2194
轮回少年
轮回少年 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-09 17:38

    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.

提交回复
热议问题