Home  >  Article  >  Java  >  In Java, how do we compare StringBuilder and StringBuffer?

In Java, how do we compare StringBuilder and StringBuffer?

王林
王林forward
2023-08-28 15:57:061078browse

In Java, how do we compare StringBuilder and StringBuffer?

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.

Example

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) &#39;a&#39;);
      }
      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) &#39;a&#39;);
      }
      System.out.println("StringBuilder test: " + (System.nanoTime() - startTime));
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete