近几天,看老大的框架,里面出现这样的语句for (int i = 0, size = c.size(); i < size; i++),我总觉得这个和for (int i = 0; i < c.size(); i++)没有什么不同,毕竟java不是C,一般情况下,我们程序给运行了,底层JVM应该给我们优化才是。于是,我写了个程序对比了一下,发现性能情况还是很大不同的。
package com.wang.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class Test {
    private final static int Length = 1000;
    public static void main(String[] args) {
        int length = 1000;
        List<Double> c = new ArrayList<Double>();
        initSet(c);
        long t1 = System.currentTimeMillis();
        test1(c);
        long t2 = System.currentTimeMillis();
        test2(c);
        long t3 = System.currentTimeMillis();
        test3(c);
        long t4 = System.currentTimeMillis();
        test4(c);
        long t5 = System.currentTimeMillis();
        System.out
                .println("*******************************************************************");
        System.out.println(t2 - t1);
        System.out.println(t3 - t2);
        System.out.println(t4 - t3);
        System.out.println(t5 - t4);
    }
    private static void test3(List<Double> c) {
        for (Iterator<Double> iterator = c.iterator(); iterator.hasNext();) {
            System.out.println(iterator.next());
        }
    }
    private static void test2(List<Double> c) {
        for (int i = 0; i < c.size(); i++) {
            System.out.println(c.get(i));
        }
    }
    private static void test4(List<Double> c) {
        for (int i = c.size() - 1; i >= 0; i--) {
            System.out.println(c.get(i));
        }
    }
    private static void test1(List<Double> c) {
        for (int i = 0, size = c.size(); i < size; i++) {
            System.out.println(c.get(i));
        }
    }
    private static void initSet(List<Double> c) {
        for (int i = 0; i < Length; i++) {
            c.add(Math.random());
        }
    }
}
Length==1000时:
94
62
32
31
Length==10000时:
516
406
375
344
Length==100000时:
3563
3453
3641
3453
Length==1000000时:
35109
34625
36469
34891
JVM到底有没有优化呢。我没有打开汇编看。但至少我得出结论:for (int i = 0, size = c.size(); i < size; i++)这种写法没有必要。数据量不大的时候,反而效率低很多。
各位高手给建议。。。。。。。Why