Java中遍历字符串toCharArray()和charAt()效率比较

public static void test() {  
    String s = "a";  
    for(int i = 0; i < 100000; i++) {  
        s += "a";  
    }  
    /****************toCharArray遍历*************/  
    long start1 = System.currentTimeMillis();  
    char[] arr = s.toCharArray();  
    for (int i = 0; i < arr.length; i++) {
         char c = arr[i];
         System.out.println(c);
    }
    long end1 = System.currentTimeMillis();  
    /****************charAt遍历******************/    
    long start2 = System.currentTimeMillis();  
    for(int i = 0; i < s.length(); i++) {  
        char c = s.charAt(i);  
        System.out.println(c);  
    }  
    long end2 = System.currentTimeMillis();  
          
    System.out.println(end1 - start1);  //503
    System.out.println(end2 - start2);  //453
}  

由此得出charAt效率较高。

转载于:https://www.cnblogs.com/lxcmyf/p/8805547.html

你可能感兴趣的:(java)