Is it better coding practice to define variables outside a foreach even though more verbose?

前端 未结 12 2255
栀梦
栀梦 2020-12-10 10:39

In the following examples:

  • the first seems more verbose but less wasteful of resources
  • the second is less verbose bu
12条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 11:16

    Personally, I think it's the best practice to declare variables in the tightest scope possible, given their usage.

    This provides many benefits:

    1. It's easier for refactoring, since extracting a method is simpler when the variables are already in the same scope.
    2. The variable usage is more clear, which will lead to more reliable code.

    The only (potential) disadvantage would be the extra variable declaration - however, the JIT tends to optimize this issue away, so it's one I wouldn't necessarily worry about in real work.

    The one exception to this:

    If your variable is going to be adding a lot of GC pressure, and if this can be avoided by reusing the same object instance through the foreach/for loop, and if the GC pressure is causing measured performance problems, I'd lift it into the outer scope.

提交回复
热议问题