Difference between declaring variables before or in loop?

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

    There is a difference in C# if you are using the variable in a lambda, etc. But in general the compiler will basically do the same thing, assuming the variable is only used within the loop.

    Given that they are basically the same: Note that version b makes it much more obvious to readers that the variable isn't, and can't, be used after the loop. Additionally, version b is much more easily refactored. It is more difficult to extract the loop body into its own method in version a. Moreover, version b assures you that there is no side effect to such a refactoring.

    Hence, version a annoys me to no end, because there's no benefit to it and it makes it much more difficult to reason about the code...

提交回复
热议问题