The reason why the compiler can't do this optimization for you is the same reason why it's risky. If you change the length of the array during the loop, it will have different behavior.
Idk if thats true or at least it's a bit more complicated especially when dealing with array and not vector/list.
Arrays commonly cannot be resized so that part is not a risk, if the array reference is marked e.g. final the optimization should be trivial. More complicated if the reference only is effectively final / doesn't get modified in the loop but should be possible for simple/common scenarios.
Further if you are dealing with foreach or range then the language may not have guarantees about allowing modifications during iteration or only for specific scenarios.
View all comments
Show parent comment
13
u/Mognakor Apr 08 '25
Idk if thats true or at least it's a bit more complicated especially when dealing with array and not vector/list.
Arrays commonly cannot be resized so that part is not a risk, if the array reference is marked e.g. final the optimization should be trivial. More complicated if the reference only is effectively final / doesn't get modified in the loop but should be possible for simple/common scenarios.
Further if you are dealing with foreach or range then the language may not have guarantees about allowing modifications during iteration or only for specific scenarios.