本文介绍了在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中,是否应该在循环的每次迭代或循环之前定义一个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!