Comparison of String and StringBuffer efficiency in splicing operation in Java

The String type is immutable in java, which means immutable. Every time String is spliced, it is actually a new String in the jvm. The more times String is new, the slower the virtual machine speed will be.
The internal of StringBuffer is actually a character array. For different jdk s, you can use the following methods to view their actual size and capacity (please refer to the following code). Note: These are two different concepts. Please refer to the API documentation for details.

String str1 = "redpig";
StringBuffer sb = new StringBuffer(str1);
System.out.println(sb.length()); //Content length
System.out.println(sb.capacity());//Total space

If 10 characters are randomly generated each time (only case letters and numbers) and repeated 10000 times, the running efficiency of String and StringBuffer can be clearly seen.

import java.util.Random;

public class TestStrAndStrBuf {

    private static char[] characterPool = new char[62];

    static {
        char c = 0;
        int i = 0;
        for (c = 'a'; c < 'z'; c++, i++)
            characterPool[i] = c;
        for (c = 'A'; c < 'Z'; c++, i++)
            characterPool[i] = c;
        for (c = '0'; c < '9'; c++, i++)
            characterPool[i] = c;
    }

    public static void main(String[] args) {
        appendString(10000, 10);
        appendStringBuffer(10000, 10);
    }

    public static char[] getRandomCharacters(int charactersLength) {
        char[] chars = new char[charactersLength];
        Random r = new Random();
        for (int i = 0; i < charactersLength; i++)
            chars[i] = characterPool[Math.abs(r.nextInt()) % characterPool.length];
        return chars;
    }

    public static void appendString(int times, int charactersLength) {
        String string = new String();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < times; i++)
            string += String.valueOf(getRandomCharacters(charactersLength));
        long endTime = System.currentTimeMillis();
        System.out.println("Run time is " + (endTime - startTime));
    }

    public static void appendStringBuffer(int times, int charactersLength) {
        StringBuffer stringBuffer = new StringBuffer();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < times; i++)
            stringBuffer.append(getRandomCharacters(charactersLength));
        long endTime = System.currentTimeMillis();
        System.out.println("Run time is " + (endTime - startTime));
    }

}

The results of different hardware and software are different. The effect of this machine is as follows:

Therefore, for applications with frequent character changes, please use StringBuffer!

Tags: Java jvm JDK

Posted on Mon, 02 Dec 2019 19:21:10 -0800 by justcrapx