比较一下String.split方法和indexOf + subString方法截取字符串

直接上代码

public static void main(String[] args) throws ParseException{
    String str = "AB123456";
    long start = System.currentTimeMillis();
    for(int i = 0 ; i < 10 * 10000 ; i ++){
        String[] lines = str.split("\\D+");
    }
    long end = System.currentTimeMillis();
    System.out.println("split time consumed:" + (end - start) / 1000.0 + "s");
    
    start = System.currentTimeMillis();
    int index = -1;
    for(int i = 0 ; i < 10 * 10000 ; i ++){
        index = -1;
        for(int k = 0 ; k < str.length() ; k ++){
            if(str.charAt(k) >= '0' && str.charAt(k) <= '9'){
                index = k;
                break;
            }
        }
        
        if(index > 0){
            String[] lines = new String[]{str.substring(0, index),str.substring(index)};
        }
    }
    end = System.currentTimeMillis();
    System.out.println("indexof time consumed:" + (end - start) / 1000.0 + "s");
}
以下是输出结果:

split time consumed:0.104s
indexof time consumed:0.007s

虽然表面上看,split比index + subString要简单很多,但后者性能是前者的将近15倍。

posted @ 2019-10-21 16:04  Pei你看雪  阅读(17)  评论(0)    收藏  举报  来源