lua-users home
lua-l archive

Re: questions about closure construction

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 19/03/2013 6:47 PM, steve donovan wrote:
On Tue, Mar 19, 2013 at 4:27 AM, Ross Bencina
<rossb-lists@audiomulch.com> wrote:
>function __y_bar(self) print "y" end
>function Y()
> return { foo = __y_bar }
>end
>function Z()
> local function __z_bar(self) print "z" end
> return { foo = __z_bar }
>end
>
>Z runs slower than X or Y, suggesting that there is some runtime overhead in
>creating a named local variable (which surprises me, seems like a simple
>optimisation).
>
Yes, indeed; in Z you create a closure each time, which is a dynamic
object (much as how {} is a 'table constructor' not a 'table
literal').
Thanks Steve, that helps.
I wonder whether the language guarantees unique identities for separately constructed closures:
function Z()
 local function __z_bar(self) print "z" end
 return { foo = __z_bar }
end
assert( Z().foo ~= Z().foo )
That might also place some boundaries on expectations.
> I believe Lua 5.2 has made some progress in re-using closures that
> have no upvalues.
That's interesting. It means that the "inline local functions with no upvalues" may still be a valid idiom for performance-critical code.
Do you remember where this was discussed?
> LuaJIT may well optimize it to nothing ;)
I guess my main target is the notional language specification rather than any specific interpreter. If I know that "function" is likely to always cost more than x = a.y; then I will take due care to "pre-construct" my functions.
Ross.

AltStyle によって変換されたページ (->オリジナル) /