kikito
kikito

Reputation: 52641

Lua: performance of __index as a function vs as a table

In Lua the the __index metamethod can be either a function or a table reference. So the following constructions are equivalent:

foo = { a=1, b=2, c=3 }
bar = setmetatable({}, {__index = foo})
baz = setmetatable({}, {__index = function(_,x) return foo[x] end })

print(bar.a) -- 1
print(baz.b) -- 2

It would seem that the baz implementation would be slower.

But how much slower?

I don't care much about implementation differences. What I'm looking for is the 'general' comparative difference. Are we talking about a linear increment, one order of magnitude, or several orders?

To give some context: I'm developing a oop library where in the most common circumstances (95%) a table is enough. But there's one specific case in which I need a function. Knowing the difference will help me decide whether to 'split' the library in two (one fast and covering 95% of the uses, and one module that uses functions for the rest) or just dumping the table option in favor of the function.

This particular __index is used extensively (every time an instance method is invoked).

If that helps, the function I'll be using will be very small, similar to this:

function __index(t,x) return foo[x] or bar[x] end

Thanks a lot.

Upvotes: 4

Views: 3211

Answers (1)

Mud
Mud

Reputation: 28991

Algorithmically they are they same. They both resolve to the same hashtable lookup, average time O(1). The difference is constant, mostly from the function call overhead.

On my machine the closure is ~2.2 times slower than the metatable lookup (which is 2.5 times slower than a direct lookup). Testing on Codepad's server, the difference is ~2.

Bottom line, on a fast machine (circa 2010), the function call is adding about a tenth of a microsecond of constant overhead, otherwise the performance is the same.

BTW, much LÖVE from Mud. :)

Upvotes: 10

Related Questions