Table of Contents
In this post, we will see difference between StringBuffer and StringBuilder in java
StringBuffer vs StringBuilder
Performance comparison between StringBuffer and StringBuilder in single thread environment
When you run above program, you may get below output:
You can go through core java interview questions for more such questions.
|
Parameter
|
StringBuffer
|
StringBuilder
|
|---|---|---|
|
Thread-safe
|
StringBuffer is thread safe. Two threads can not call methods of StringBuffer simultaneously.
|
StringBuilder is not thread safe, so two threads can call methods of StringBuilder simultaneously.
|
|
Performance
|
It is less performance efficient as it is thread-safe |
It is more performance efficient as it is not thread-safe.
|
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package org.arpit.java2blog; public class StringBuilderAndBufferMainTest { public static void main(String[] args) { long startTime = System.currentTimeMillis(); StringBuffer sb = new StringBuffer("Java"); for (int i=0; i<100000; i++){ sb.append("2Blog"); } System.out.println("Time taken by StringBuffer: " + (System.currentTimeMillis() - startTime) + "ms"); startTime = System.currentTimeMillis(); StringBuilder sbuilder = new StringBuilder("Java"); for (int i=0; i<100000; i++){ sbuilder.append("2Blog"); } System.out.println("Time taken by StringBuilder: " + (System.currentTimeMillis() - startTime) + "ms"); } } |
|
1 2 3 4 |
Time taken by StringBuffer: 21ms Time taken by StringBuilder: 9ms |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.