I've always remembered that it's faster to do String-type character concatenation with the StringBuilder append from my superior at the previous site, but the reference book I'm studying now also mentions that. So I wanted to practice how fast it really is.
stringBuilderTest.java
public class StringBuilderTest {
public static void main(String[] args) {
String name = "";
long start = System.currentTimeMillis();
for(int i=1; i<=1000; i++){
name += "tanaka, ";
};
long end = System.currentTimeMillis();
System.out.println("+Linking: "+(end - start) + "ms");
StringBuilder sb = new StringBuilder();
long start2 = System.currentTimeMillis();
for(int i=1; i<=400000; i++){
sb.append("tanaka, ");
};
String name2 = sb.toString();
long end2 = System.currentTimeMillis();
System.out.println("StringBuilder.append concatenation: "+(end2 - start2) + "ms");
}
}
result.java
+Linking: 24ms
StringBuilder.append concatenation: 27ms
As you can see from the number of times the for statement is turned, it takes 24ms
to execute 1000 times for concatenation with +, and append concatenation is executed 400,000 times with 27ms
.
Even if you only execute it a few times, it's worth remembering that the previous site also ran the for statement in units of 10,000.