Вопрос-ответ

Difference between StringBuilder and StringBuffer

Разница между StringBuilder и StringBuffer

В чем основное различие между StringBuffer и StringBuilder? Есть ли какие-либо проблемы с производительностью при выборе любого из них?

Переведено автоматически
Ответ 1

StringBuffer синхронизирован, StringBuilder нет.

Ответ 2

StringBuilder быстрее, чем StringBuffer потому что это не так synchronized.

Вот простой бенчмарковый тест:

public class Main {
public static void main(String[] args) {
int N = 77777777;
long t;

{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = N; i --> 0 ;) {
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}

{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = N; i > 0 ; i--) {
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
}
}

Тестовый запуск выдает числа 2241 ms for StringBuffer против 753 ms for StringBuilder.

Ответ 3

В принципе, StringBuffer методы синхронизируются, а StringBuilder нет.

The operations are "almost" the same, but using synchronized methods in a single thread is overkill.

That's pretty much about it.

Quote from StringBuilder API:


This class [StringBuilder] provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.


So it was made to substitute it.

The same happened with Vector and ArrayList.

Ответ 4

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.

java