lua-users home
lua-l archive

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


Paul Chiusano wrote:
> My question is: is there a performance penalty associated with doing
> this?

It doesn't affect other primitive operations on numbers, so there
is no performance penalty for _them_.

But you make the core do some extra work to just call a function.
This is of course slower than directly calling it.

> Does adding this metatable cause all numeric operations to
> perform slower?


> Also, I notice that overriding any of the operator
> metamethods (like __div) for numbers has no effect. Is this for
> performance reasons?

Yes, very much so. Requiring a check for every primitive
operation on numbers would slow Lua to a crawl.

PA wrote:
> I was wondering about this as well. Furthermore, why isn't the math 
> package the default metatable for numbers in the same way as the string
> package is for strings?

Because it doesn't pay off. It's slower than calling the
functions directly. And it doesn't help to improve the clarity of
the code (x:sin():sqrt() vs. sqrt(sin(x))). I guess OO syntax for
math functions never caught on.

The performance caveat applies to the use of string metamethods,
too. But other languages provide an OO syntax for string ops and
some people like the syntax.

$ time lua -e 'local s=""; for i=1,1e7 do local y=s:len() end'
$ time lua -e 'local s,len="",string.len; for i=1,1e7 do local y=len(s) end'
$ time lua -e 'local s=""; for i=1,1e7 do local y=#s end'

[Lower numbers are better.]