Difference between declaring variables before or in loop?

前端 未结 25 2471
长发绾君心
长发绾君心 2020-11-22 02:37

I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference? A (q

25条回答
  •  轮回少年
    2020-11-22 03:19

    From a performance perspective, outside is (much) better.

    public static void outside() {
        double intermediateResult;
        for(int i=0; i < Integer.MAX_VALUE; i++){
            intermediateResult = i;
        }
    }
    
    public static void inside() {
        for(int i=0; i < Integer.MAX_VALUE; i++){
            double intermediateResult = i;
        }
    }
    

    I executed both functions 1 billion times each. outside() took 65 milliseconds. inside() took 1.5 seconds.

提交回复
热议问题