String, StringBuffer, and StringBuilder

后端 未结 11 1558
谎友^
谎友^ 2020-11-22 13:52

Please tell me a real time situation to compare String, StringBuffer, and StringBuilder?

11条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 14:23

    • You use String when an immutable structure is appropriate; obtaining a new character sequence from a String may carry an unacceptable performance penalty, either in CPU time or memory (obtaining substrings is CPU efficient because the data is not copied, but this means a potentially much larger amount of data may remain allocated).
    • You use StringBuilder when you need to create a mutable character sequence, usually to concatenate several character sequences together.
    • You use StringBuffer in the same circumstances you would use StringBuilder, but when changes to the underlying string must be synchronized (because several threads are reading/modifyind the string buffer).

    See an example here.

提交回复
热议问题