scope of local variable in enhanced for-loop

后端 未结 5 1156
执念已碎
执念已碎 2021-01-18 02:00

I have a rather simple question about variable scope.

I am familiar with the Enhanced For-Loops but I do not get why I should declare a new variable to keep each el

5条回答
  •  攒了一身酷
    2021-01-18 02:47

    Does this means that I have a local variable that gets different values or a different variable in each loop?

    From a language point of view you have a different variable in each iteration. That’s why you can write:

    for(final ItemType item: iterable) {
      …
    }
    

    which makes a great difference as you can create inner class instances within the loop referring to the current element. With Java 8 you can use lambdas as well and even omit the final modifier but the semantic does not change: you don’t get the surprising results like in C#.

    I guessed for other iterable items it might be faster using the same variable

    That’s nonsense. As long as you don’t have a clue of how the produced code looks like you shouldn’t even guess.

    But if you are interested in the details of Java byte code: within a stack frame local variables are addressed by a number rather than by a name. And the local variables of your program are mapped to these storage locations by reusing the storage of local variables that went out of scope. It makes no difference whether the variable exists during the entire loop or is “recreated” on every iteration. It will still occupy just one slot within the stack frame. Hence, trying to “reuse local variables” on a source code level makes no sense at all. It just makes your program less readable.

提交回复
热议问题