Difference between declaring variables before or in loop?

前端 未结 25 2121
长发绾君心
长发绾君心 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:08

    I would always use A (rather than relying on the compiler) and might also rewrite to:

    for(int i=0, double intermediateResult=0; i<1000; i++){
        intermediateResult = i;
        System.out.println(intermediateResult);
    }
    

    This still restricts intermediateResult to the loop's scope, but doesn't redeclare during each iteration.

提交回复
热议问题