Difference between StringBuilder and StringBuffer

后端 未结 30 2405
独厮守ぢ
独厮守ぢ 2020-11-21 15:06

What is the main difference between StringBuffer and StringBuilder? Is there any performance issues when deciding on any one of these?

30条回答
  •  梦如初夏
    2020-11-21 15:30

    But needed to get the clear difference with the help of an example?

    StringBuffer or StringBuilder

    Simply use StringBuilder unless you really are trying to share a buffer between threads. StringBuilder is the unsynchronized (less overhead = more efficient) younger brother of the original synchronized StringBuffer class.

    StringBuffer came first. Sun was concerned with correctness under all conditions, so they made it synchronized to make it thread-safe just in case.

    StringBuilder came later. Most of the uses of StringBuffer were single-thread and unnecessarily paying the cost of the synchronization.

    Since StringBuilder is a drop-in replacement for StringBuffer without the synchronization, there would not be differences between any examples.

    If you are trying to share between threads, you can use StringBuffer, but consider whether higher-level synchronization is necessary, e.g. perhaps instead of using StringBuffer, should you synchronize the methods that use the StringBuilder.

提交回复
热议问题