5

Specifically in Lua, will I do any harm by doing this:

for i = 1, 10 do
    local foo = bar()
    -- do stuff with foo
end

instead of this:

local foo
for i = 1, 10 do
    foo = bar()
    -- do stuff with foo
end

I mean, will Lua try to allocate new memory for foo every iteration? Could the first block lead to slower execution?

Yuri Ghensev
  • 2,507
  • 4
  • 28
  • 45
  • actually I made some simple tests and there was no difference – Yuri Ghensev Dec 29 '10 at 17:22
  • 4
    Also, see the output of `luac -l` to see the VM code. – lhf Dec 29 '10 at 17:23
  • 1
    You may find more elaborate answers on this duplicate question: [Is it better to declare a local inside or outside a loop?](https://stackoverflow.com/questions/31083951/is-it-better-to-declare-a-local-inside-or-outside-a-loop) – Gras Double Jun 21 '20 at 03:58

1 Answers1

6

Go for the safest alternative, which is to use the smallest scope for all variables. As for efficiency, local variables are stored in a stack; no memory allocation is done inside the loop.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • @arkilus Remember to upvote answers you accept. It is done by clicking the arrow pointing up. – ponzao Dec 29 '10 at 17:55
  • @ponzao I thought that was needed only when there were more than one answer. Anyway, already did, thanks. – Yuri Ghensev Dec 29 '10 at 18:09
  • 1
    @arkilus You're welcome! (You should upvote answers that you find helpful. The accepted answer is the one that solves your question.) – ponzao Dec 30 '10 at 09:34