Difference between declaring variables before or in loop?

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

    Even if I know my compiler is smart enough, I won't like to rely on it, and will use the a) variant.

    The b) variant makes sense to me only if you desperately need to make the intermediateResult unavailable after the loop body. But I can't imagine such desperate situation, anyway....

    EDIT: Jon Skeet made a very good point, showing that variable declaration inside a loop can make an actual semantic difference.

    0 讨论(0)
提交回复
热议问题