[Java] String join execution speed comparison (+ operator vs StringBuilder)

Introduction

Repeat "hoge" 100,000 times to connect.

+ Operator

String result = "";
  for (var i = 0; i < 100000; i++) {
  result += "Hoge";
}

StringBuilder

var builder = new StringBuilder();
for (var i = 0; i < 100000; i++) {
  builder.append("Hoge");
}
var result = builder.toString();

Execution result

Execution time (ms)
+ Operator 5709
StringBuilder 9

Summary

Overwhelming StringBuilder victory. It seems that the method of concatenating with the + operator takes time because the String object is created / destroyed repeatedly internally.

Recommended Posts

[Java] String join execution speed comparison (+ operator vs StringBuilder)
[Java] Speed comparison of string concatenation
Speed comparison test for String, StringBuilder, StringBuffer
[Java] String comparison and && and ||
Java --StringBuilder vs StringBuffer
[Java] Type conversion speed comparison
[Java] About String and StringBuilder
Studying Java 8 (String Joiner and join)
[Java] Correct comparison of String type
Regarding String type equivalence comparison in Java
[Java] Collection and StringBuilder operation method comparison
[Java] Comparison of String type character strings
Java string
The story of low-level string comparison in Java
[Java] The confusing part of String and StringBuilder
[Note] Java: Measures the speed of string concatenation
Why Java String typeclass comparison (==) cannot be used
[Verification] Comparison of Spring Boot vs Micronaut boot speed