[Java] [Memorandum] Java: Measure the speed of string concatenation

less than 1 minute read

Introduction

I’ve always remembered that I was faster from the point of view of string concatenation with append of StringBuilder in the previous field, but it was mentioned in the reference book I am studying now. 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("+ concatenation: "+(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


        + Connection: 24ms
        StringBuilder.append concatenation: 27ms

You can see that you can see the number of times the for statement is turning, but the + concatenation takes 1000 times to execute 24ms, and the append concatenation executes 27ms for 400,000 times. Even if it is only executed a few times, there is no loss in remembering it because the previous site also used a for statement for every 10,000 units.

Tags:

Updated: