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

In Java, how do we compare StringBuilder and StringBuffer?

王林
Release: 2023-08-28 15:57:06
forward
1168 people have browsed it

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));
   }
}
Copy after login

Output

StringBuffer test: 192595
StringBuilder test: 85733
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template