ArrayList的不同的遍历方式性能比较,其实都差不了多少

JAVA学习网 2017-09-03 13:16:01
//RadomAcess的接口for..i的遍历比for..loop的快,@more see comments for interface RandomAcess 
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
public class ListPerformanceTest {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        for(int i = 0; i < Integer.MAX_VALUE / 200; i++) {
            list.add("1");
        }
        long d1 = System.currentTimeMillis();
        /***************** fastest ************************/
//        for(int i = 0, n = list.size(); i < n; i++) {
//            list.get(i);
//        }
        /***************** second fastest due to each loop would get the list size ************************/
//        for(int i = 0; i < list.size(); i++) {
//            list.get(i);
//        }
        /***************** not know why this is faster than the last ************************/
//        for(Iterator<?> it = list.iterator(); it.hasNext();) {
//            it.next();
//        }
 
//        for(String s : list) {
//            if(s != null) {
//                continue;
//            }
//        }
        System.out.println("Times(ms):" + (System.currentTimeMillis() - d1));
    }
}
阅读(806) 评论(0)