StringBuffer objects are generally safe to use in multithreaded environments where multiple threads may attempt to access the same StringBufferObject at the same time. StringBuilder is a thread-safe replacement for the StringBuffer class that works much faster because it does not synchronize > method. If we perform a lot of string operations in a single thread, using this class can improve performance.
public class CompareBuilderwithBufferTest { public static void main(String []args) { <strong> </strong> stringBufferTest(); stringBuilderTest();<strong> </strong> } public static void stringBufferTest() { long startTime = System.nanoTime(); StringBuffer sb = new StringBuffer(); for (int i=0; i < 1000; i++) { sb.append((char) 'a'); } System.out.println("StringBuffer test: " + (System.nanoTime() - startTime)); } public static void stringBuilderTest()<strong> </strong>{ long startTime = System.nanoTime(); StringBuilder sb = new StringBuilder(); for (int i=0; i < 1000; i++) { sb.append((char) 'a'); } System.out.println("StringBuilder test: " + (System.nanoTime() - startTime)); } }
StringBuffer test: 192595 StringBuilder test: 85733
The above is the detailed content of In Java, how do we compare StringBuilder and StringBuffer?. For more information, please follow other related articles on the PHP Chinese website!