English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Differenza tra buffer di stringa e generatore di stringhe in Java

Le String Buffer e StringBuilder sono classi mutabili, utilizzate per eseguire operazioni su oggetti stringa, come la reversione delle stringhe, la compressione delle stringhe, ecc. Possiamo modificare la stringa senza creare nuovi oggetti stringa. Il String Buffer è thread-safe, mentre il String Builder non è thread-safe. Pertanto, è più veloce. Inoltre, l'operatore di concatena + utilizza internamente la classe StringBuffer o StringBuilder. Ecco le differenze.

IndexKeyString bufferString generator
1
Basic

StringBuffer was introduced in the initial version of Java

It was introduced in Java 5
2
Synchronous
It is synchronousAsynchronous 
3Performance 

It is thread-safe. Therefore, multiple threads cannot access it at the same time, so it is slow.

It is not thread-safe, so it is faster than the string buffer 
4Mutable

It is mutable. We can modify the string without creating an object

It is also mutable 
5
Storage 
Heap
Heap

StringBuilder example

public class StringBuilderExample{
   public static void main(String[] args){
      StringBuilder builder = new StringBuilder("Hi");
      builder.append("Java 8");
      System.out.println("StringBuilderExample" + builder);
   {}
{}

StringBuffer example

public class StringBufferExample{
   public static void main(String[] args){
      StringBuffer buffer = new StringBuffer("Hi");
      buffer.append("Java 8");
      System.out.println("StringBufferExample" + buffer);
   {}
{}