Java中遍历方法对比

Demo

public class Test {

    public static void main(String[] args) {
        test(10);
        test(100);
        test(1000);
        test(10000);
    }

    public static void test(int size) {
        //1.组装数组
        List<String> list = list(size);
        long nanoTime = System.nanoTime();
        //2.普通for循环
        testFor(list);
        long nanoTime1 = System.nanoTime();
        //3.增强for循环
        testForeach(list);
        long nanoTime2 = System.nanoTime();
        //4.java8for循环
        testJava8forEach(list);
        long nanoTime3 = System.nanoTime();
        System.out.println("普通for循环" + (int) (nanoTime1 - nanoTime) / 1000 + "ms");
        System.out.println("增强for循环" + (int) (nanoTime2 - nanoTime1) / 1000 + "ms");
        System.out.println("java8for循环" + (int) (nanoTime3 - nanoTime2) / 1000 + "ms");
        System.out.println("-------------------------------------------------");
    }

    /**
     * 普通for循环
     *
     * @param list
     */
    public static void testFor(List<String> list) {
        for (int i = 0; i < list.size(); i++) {
            list.get(i).hashCode();
        }
    }

    /**
     * 增强for循环
     *
     * @param list
     */
    public static void testForeach(List<String> list) {
        for (String s : list) {
            s.hashCode();
        }
    }

    /**
     * java8for循环
     *
     * @param list
     */
    public static void testJava8forEach(List<String> list) {
        list.forEach(str -> str.hashCode());
    }

    public static List<String> list(int size) {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            list.add(i + "hello world");
        }
        return list;
    }
}

运行输出

普通for循环257ms
增强for循环4948ms
java8for循环378608ms
-------------------------------------------------
普通for循环125ms
增强for循环67ms
java8for循环371ms
-------------------------------------------------
普通for循环363ms
增强for循环530ms
java8for循环601ms
-------------------------------------------------
普通for循环2391ms
增强for循环1719ms
java8for循环1546ms
-------------------------------------------------
posted @ 2024-01-21 16:04  leepandar  阅读(8)  评论(0编辑  收藏  举报