Difference between StringBuilder and StringBuffer

At the beginning

"Please explain the difference between StringBuilder and StringBuffer." Said, "String Builder has better performance !!" I could only answer.

So this time I tried to verify why StringBuilder has good performance and how much the speed difference is.

Different place

StringBuilder: Not thread safe StringBuffer: Threadsafe

That was all. According to Tiger who introduced StringBuilder "Do you need thread safety for string concatenation?" It seems that it was made with the idea.

String Manipulation Threadsafe vs Performance StringBuilder

Certainly I have never seen string concatenation that requires thread safety. It's a place that many people used without much concern, but I think it's amazing to catch it.

Verification

I tried to verify it easily. We have adopted this verification method. [Java] I tried to verify the difference between StringBuilder and StringBuffer from the viewpoint of thread safety

Share the same StringBuilder / StringBuffer instance with 100 threads and repeat append 10,000 times. As a result, we are seeing if length () is correctly 1 million. The processing speed was also measured.

StringBuilderTest.java


public class StringBuilderTest {
  
	public static void main (String... args) throws InterruptedException {
		ExecutorService executor = Executors.newFixedThreadPool(100);
		StringBuilder sb = new StringBuilder();
		List<BuilderTask> taskList = new ArrayList<BuilderTask>();
		
		for(int i = 0; i < 100; i++) {
			taskList.add(new BuilderTask(sb));
		}
		
		Long start = System.currentTimeMillis();
		
		executor.invokeAll(taskList);
		
		System.out.println("-----StringBuilder-----");
		System.out.println("TAT : " + (System.currentTimeMillis() - start));
		System.out.println("length() : " + sb.length());
	}
	
	static class BuilderTask implements Callable<Integer> {
		private StringBuilder sb;
		
		public BuilderTask(StringBuilder sb) {
			this.sb = sb;
		}

		@Override
		public Integer call() throws Exception {
			for(int i = 0; i < 10000; i++) {
				sb.append("#");				
			}
			return null;
		}
	}
}

StringBufferTest.java


public class StringBufferTest {
  
	public static void main (String... args) throws InterruptedException {
		ExecutorService executor = Executors.newFixedThreadPool(100);
		StringBuffer sb = new StringBuffer();
		List<BufferTask> taskList = new ArrayList<BufferTask>();
		
		for(int i = 0; i < 100; i++) {
			taskList.add(new BufferTask(sb));
		}
		
		Long start = System.currentTimeMillis();
		
		executor.invokeAll(taskList);
		
		System.out.println("-----StringBuffer-----");
		System.out.println("TAT : " + (System.currentTimeMillis() - start));
		System.out.println("length() : " + sb.length());
	}
	
	static class BufferTask implements Callable<Integer> {
		private StringBuffer sb;
		
		public BufferTask(StringBuffer sb) {
			this.sb = sb;
		}

		@Override
		public Integer call() throws Exception {
			for(int i = 0; i < 10000; i++) {
				sb.append("#");				
			}
			return null;
		}
	}
}

result

-----StringBuilder-----
TAT : 32
length() : 542861

-----StringBuffer-----
TAT : 157
length() : 1000000

With StringBuilder, almost half of the characters were lost. Instead, the processing speed is about 5 times faster.

It's hard to imagine when thread-safe string concatenation is needed in real business, so I think I'll use StringBuilder with a focus on performance.

Recommended Posts

Difference between StringBuilder and StringBuffer
[Java] Difference between StringBuffer and StringBuilder
Difference between vh and%
Difference between i ++ and ++ i
Difference between product and variant
Difference between redirect_to and render
[Java] Difference between == and equals
Rails: Difference between resources and resources
Difference between redirect_to and render
Difference between CUI and GUI
Difference between variables and instance variables
Difference between mockito-core and mockito-all
Difference between class and instance
Difference between bundle and bundle install
Difference between ArrayList and LinkedList
Difference between render and redirect_to
Difference between List and ArrayList
Difference between render and redirect_to
Difference between render and redirect_to
[Ruby] Difference between get and post
Difference between instance method and class method
Difference between render method and redirect_to
Difference between interface and abstract class
Difference between == operator and equals method
[Java] Difference between Hashmap and HashTable
[Terminal] Difference between irb and pry
JavaServlet: Difference between executeQuery and executeUpdate
[Ruby] Difference between is_a? And instance_of?
Difference between == operator and eqals method
Rough difference between RSpec and minitest
[Rails] Difference between find and find_by
Understand the difference between each_with_index and each.with_index
Difference between instance variable and class variable
StringBuffer and StringBuilder Class in Java
[JAVA] Difference between abstract and interface
Difference between Thymeleaf @RestController and @Controller
[Java] Difference between array and ArrayList
Difference between primitive type and reference type
[Java] Difference between Closeable and AutoCloseable
[Java] Difference between length, length () and size ()
[rails] Difference between redirect_to and render
[Android] Difference between finish (); and return;
Note: Difference between Ruby "p" and "puts"
Difference between final and Immutable in Java
[Memo] Difference between bundle install and update
Difference between Ruby instance variable and local variable
Difference between pop () and peek () in stack
[For beginners] Difference between Java and Kotlin
Difference between isEmpty and isBlank of StringUtils
Difference between getText () and getAttribute () in Selenium
About the difference between irb and pry
Difference between "|| =" and "instance_variable_defined?" In Ruby memoization
Difference between EMPTY_ELEMENTDATA and DEFAULTCAPACITY_EMPTY_ELEMENTDATA in ArrayList
Difference between addPanel and presentModally of FloatingPanel
[Java] Difference between Intstream range and rangeClosed
Difference between int and Integer in Java
[Rails] Difference between redirect_to and render [Beginner]
[Java] Understand the difference between List and Set
[iOS] Understand the difference between frame and bounds
Difference between render and redirect_to, need for arguments
Difference between next () and nextLine () in Java Scanner