如何判断lua闭包和lua协程的权衡?(当它们都可以执行相同的任务时)
ps:更不用说闭包实现同一任务的代码复杂度了。
ps:let alone the code complexity of closure implementation of the same task.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
闭包的内存开销将小于协程的内存开销(除非闭包中有很多“上值”,而协程中没有)。此外,调用闭包的时间开销可以忽略不计,而调用协程的开销则很小。据我所知,Lua 在协程切换方面做得非常好,但如果性能很重要并且您可以选择不使用协程,那么您应该探索该选项。
如果您想自己进行基准测试,对于 Lua 中的此操作或其他任何操作:
您可以使用
collectgarbage("collect");collectgarbage("count")
来报告所有非垃圾可收集内存的大小。 (您可能想要“收集”几次,而不仅仅是一次。)在创建某些东西(闭包、协程)之前和之后执行此操作,以了解它消耗了多少大小。您可以使用 os.clock() 来计时。
另请参阅 Lua 编程关于分析。
The memory overhead for a closure will be less than for a coroutine (unless you've got a lot of "upvalues" in the closure, and none in the coroutine). Also the time overhead for invoking the closure is negligible, whereas there is some small overhead for invoking the coroutine. From what I've seen, Lua does a pretty good job with coroutine switches, but if performance matters and you have the option not to use a coroutine, you should explore that option.
If you want to do benchmarks yourself, for this or anything else in Lua:
You use
collectgarbage("collect");collectgarbage("count")
to report the size of all non-garbage-collectable memory. (You may want to do "collect" a few times, not just one.) Do that before and after creating something (a closure, a coroutine) to know how much size it consumes.You use
os.clock()
to time things.See also Programming in Lua on profiling.
参见:
https://gist.github.com/LiXizhi/911069b7e7f98db76d295dc7d1c5e34a
see also:
https://gist.github.com/LiXizhi/911069b7e7f98db76d295dc7d1c5e34a