在 Lua 中,我应该在循环的每次迭代中还是在循环之前定义一个变量? [英] In Lua, should I define a variable every iteration of a loop or before the loop?
本文介绍了在 Lua 中,我应该在循环的每次迭代中还是在循环之前定义一个变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
特别是在 Lua 中,这样做会不会对我造成任何伤害:
Specifically in Lua, will I do any harm by doing this:
for i = 1, 10 do
local foo = bar()
-- do stuff with foo
end
而不是这个:
local foo
for i = 1, 10 do
foo = bar()
-- do stuff with foo
end
我的意思是,Lua 会在每次迭代时尝试为 foo
分配新内存吗?第一个块会导致执行速度变慢吗?
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.
这篇关于在 Lua 中,我应该在循环的每次迭代中还是在循环之前定义一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文