开发者

In Lua, should I define a variable every iteration of a loop or before the loop?

开发者 https://www.devze.com 2023-02-02 04:03 出处:网络
Specifically in Lua, will I do any harm by doing this: for i = 1, 10 do local foo = bar() -- do stuff with foo

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消