Performance and simplicity tradeoffs between String, StringBuffer, and StringBuilder

后端 未结 5 2195
轮回少年
轮回少年 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:38

    Just a comment about your "StringBuilders and threads" remark: even in multi-threaded programs, it's very rare to want to build up a string across multiple threads. Typically, each thread will have some set of data and create a string from that, often by concatenating multiple strings together. They'll then convert that StringBuilder to a string, and that string can be safely shared among threads.

    I don't think I've ever seen a bug due to a StringBuilder being shared between threads.

    Personally I wish StringBuffer didn't exist - it was in the "let's synchronize everything" phase of Java, leading to Vector and Hashtable which have been almost obsoleted by the unsynchronized ArrayList and HashMap classes from Java 2. It just took a little while long for the unsynchronized equivalent of StringBuffer to arrive.

    So basically:

    • Use string when you don't want to perform manipulations, and want to be sure nothing else will
    • Use StringBuilder to perform manipulation, usually over a short period
    • Avoid StringBuffer unless you really, really need it - and as I say, I can't remember ever seeing a situation where I'd use StringBuffer instead of StringBuilder, when both are available.

提交回复
热议问题