C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Syntax: Please notice how we call the append method. We call append() on the result of another call.
Note: The append method returns an instance of the StringBuffer when it is done internally appending.
Java program that uses StringBuffer
import java.lang.StringBuffer;
public class Program {
public static void main(String[] args) {
// Create new StringBuffer.
StringBuffer buffer = new StringBuffer();
// Append three ints and spaces.
for (int i = 0; i < 3; i++) {
buffer.append(i).append(' ');
}
System.out.println(buffer);
}
}
Output
0 1 2
Version 1: This version of the code appends to the StringBuffer many times. It appends integers and chars.
Version 2: This code uses the StringBuilder class and appends the same values as version 1.
Result: The StringBuffer took over twice as much time. So the StringBuilder, in this situation, is a clear win.
Note: Other than the class name, the methods called here (append) are the same. They have equivalent effects.
Java program that benchmarks StringBuffer
import java.lang.StringBuilder;
import java.lang.StringBuffer;
public class Program {
public static void main(String[] args) {
long t1 = System.currentTimeMillis();
// Version 1: append to StringBuffer.
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < 100000; i++) {
buffer.append(i).append(' ');
}
long t2 = System.currentTimeMillis();
// Version 2: append to StringBuilder.
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100000; i++) {
builder.append(i).append(' ');
}
long t3 = System.currentTimeMillis();
// ... Times.
System.out.println(t2 - t1);
System.out.println(t3 - t2);
}
}
Output
14 ms, StringBuffer
6 ms, StringBuilder