Difference between declaring variables before or in loop?

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

    Well, you could always make a scope for that:

    { //Or if(true) if the language doesn't support making scopes like this
        double intermediateResult;
        for (int i=0; i<1000; i++) {
            intermediateResult = i;
            System.out.println(intermediateResult);
        }
    }
    

    This way you only declare the variable once, and it'll die when you leave the loop.

提交回复
热议问题