首页 > lua中的迭代器、闭包、table

lua中的迭代器、闭包、table

在programming in lua 7.4节中:

我们应该尽可能的写无状态的迭代器,因为这样循环的时候由for 来保存状态,不需要创建对象花费的代价小;如果不能用无状态的迭代器实现,应尽可能使用闭包;尽可能不要使用table 这种方式,因为创建闭包的代价要比创建 table 小,另外 Lua 处理闭包要比处理table 速度快些。后面我们还将看到另一种使用协同来创建迭代器的方式,这种方式功能更强但更复杂。

不是特别能区分无(有)状态的迭代器二者,感觉第七章读起来有些深奥。

引用中提到编写代码时 无状态的迭代器>闭包>table
我想问问这三种一种比一种代价小、速度快的具体原因。

总的来说这一章看的似懂非懂……虽然有举各种例子,详细阐述了迭代函数、状态常量、控制变量什么的……


Whenever possible, you should try to write stateless iterators, those that keep all their state in the for variables. With them, you do not create new objects when you start a loop. If you cannot fit your iteration into this model, then you should try closures. Besides being more elegant, typically a closure is more efficient than an iterator using tables: first, it is cheaper to create a closure than a table; second, access to non-local variables is faster than access to table fields.

《Programming in Lua》第三版

【热门文章】
【热门文章】