问题
ps:let alone the code complexity of closure implementation of the same task.
回答1:
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://stackoverflow.com/questions/2092910/how-to-judge-of-the-trade-off-of-lua-closure-and-lua-coroutinewhen-both-of-the