java 通过String关键词 和 String对象创建字符串 耗时对比

盘思动 / 2023-05-25 / 原文

import java.util.ArrayList;
import java.util.Vector;

public class ImoocStudent {

    public static void main(String args[]){
        long startTime = System.currentTimeMillis();
        for(int i = 0;i < 5000000;i++){
            String s1 = "hello";
            String s2 = "hello";
        }
        long endTime = System.currentTimeMillis();
        System.out.println("通过String关键词创建字符串:" + (endTime - startTime) + "ms");


        long startTime1 = System.currentTimeMillis();
        for(int i = 0;i < 5000000;i++){
            String s3 = new String("hello");
            String s4 = new String("hello");
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("通过 String 对象创建字符串:" + (endTime1 - startTime1) + "ms");
    }

}

  • https://www.runoob.com/java/string-performance.html
    不得不说m1芯片强悍啊,循环多100倍,时间还比手册的短!!!