String,StringBuffer,StringBuilder效率与内存占用比较

分别使用String,StringBuffer,StringBuilder进行10000次的字符串拼接操作,计算运行时间以及java程序运行时的内存占用。

public class StringWasteMemoryTest {
    public static void main(String[] args) {
        long beforeTime = System.currentTimeMillis();
         StringTest();
//       StringBufferTest();
//       StringBuilderTest();
        long afterTime = System.currentTimeMillis();
        System.out.println("time: " + (afterTime - beforeTime));
        long memory = Runtime.getRuntime().totalMemory()
                - Runtime.getRuntime().freeMemory();
        System.out.println("memory: " + memory);
    }

    private static void StringTest() {

        String s = "";
        for (int i = 0; i < 10000; i++) {
            s += "qwertyuiopasdfghjklzxcvbnmqazwsxedcrfvtgbyhnujmiklopplokmnjiuhbvgytfcxdrzsewaq";
        }
    }

    private static void StringBufferTest() {

        StringBuffer stringBuffer = new StringBuffer("");
        for (int i = 0; i < 10000; i++) {
            stringBuffer = stringBuffer
                    .append("qwertyuiopasdfghjklzxcvbnmqazwsxedcrfvtgbyhnujmiklopplokmnjiuhbvgytfcxdrzsewaq");
        }
    }

    private static void StringBuilderTest() {

        StringBuilder stringBuilder = new StringBuilder("");
        for (int i = 0; i < 10000; i++) {
            stringBuilder = stringBuilder
                    .append("qwertyuiopasdfghjklzxcvbnmqazwsxedcrfvtgbyhnujmiklopplokmnjiuhbvgytfcxdrzsewaq");
        }
    }
}

运行结果如下:

String:
    time: 6296
    memory: 178993040

StringBuffer:
    time: 3
    memory: 6834488

StringBuilder:
    time: 4
    memory: 6834400

StringBuffer和StringBuilder的运行效率和内存占用几乎一致,这是因为二者都是对对象本身进行操作,不会生成新的字符串对象。二者的区别主要是StringBuffer是线程安全的,而StringBuilder是线程不安全的。

String是不可变的对象,每次对String进行操作的时候,都会生成一个新的对象,这会对系统的性能造成影响。

在平时编程的过程中,如果字符串需要经常改变,应该尽量避免使用String。