Corona Quick Thought – excessive “local” in for loops

“Locals are faster than globals” is a oft-repeated Lua performance tip, and it’s true — local variables can be accessed more quickly (by index into the local environment) than less-local/more-global variables (where a wider environment must be accessed by name/key). So you tend to see a lot of “local” in Corona code, which is as it should be, though it sometimes gets carried too far.

For example, it’s not uncommon to see things like the following posted in the forums:

In both cases the local statement is unnecessary. The for loop will automatically create (and make very local) the index variables.

But additionally, it’s a bit misleading — it would seem to imply that those declared local variables will remain and retain their last values after the loop, which is not the case. The declared “i”, “k” and “v” will all be nil after the loop, since they’re never used. In fact, you’ve actually worsened performance (albeit by a minuscule amount – a single VM instruction) by causing Lua to init environment space for variables never used!

Simple take-away lesson: you need not declare index variables used in for loops.

Leave a Reply