Java StringBuffer and StringBuilder difference in the

The difference between a thread-safe:

StringBuffer is thread-safe, StringBuilder is the thread is unsafe. Because all public StringBuffer methods are used to modify synchronized, StringBuilder is not synchronized with the modified. The following figures use the append StringBuffer method and a method of StringBuilder to append Example:

StringBuffer code fragment:
Here Insert Picture Description

StringBuilder code fragment:
Here Insert Picture Description

2 difference buffer:

        StringBuffer每次toString都会直接使用toStringCache值来构造一个字符串,而StringBuilder则每次都需要复制一次字节数组,再构造一个字符串。

3 performance difference:

        StringBuffer是线程安全的,所有方法都是同步的,StringBuilder是没有对方法加锁同步的,所以StringBuilder的性能要远大于StringBuffer

to sum up:

        在使用场景为多线程时使用StringBuffer,如果是单线程则使用StringBuilder。
Released 1148 original articles · won praise 10000 + · views 420 000 +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104312077