lua-users home
lua-l archive

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

On 3-Jun-05, at 2:23 PM, Romulo Bahiense wrote:

I guess there will be no difference, because "global" funtions are not
exactly global, they are just regular functions stored in global
enviroment table, and also accessed throuth it.

There will be a performance penalty if the global table has a __index metamethod, and this is the common behaviour for compat-5.1, where each lua script has it's own environment with {__index=_G} metatable.

I don't believe you'll see much penalty from this. The __index metamethod will never be used if the key exists in the table. It will never even be checked for. Of course, if the key actually requires a metamethod lookup, there will be a slight performance penalty.

I think the more efficient solution is to store the function in a table and then lua_rawget it. I think a numeric index is faster than a string one because Lua won't need to hash it before the lookup (I repeat: I think, so I have no sure about it. Correct me if I'm wrong).

That depends on where you get the strings from. lua_rawgeti() is certainly faster than lua_pushstring() followed by lua_gettable(). However, if the string has already been interned, then the two methods are pretty similar. In Lua code itself, table.key works out to be slightly faster than table[3], at least on the configurations I've tested. (This is in part because of the need to convert 3 from float to integer, and partly because of the possible need to find the key in either the array or the hash part of the table.)

The fastest way of accessing a single function is to keep it either in a known stack slot or in an upvalue vector.

For example, if you're both loading and calling the function from the main embedding code (the one which calls lua_open), then you can simply keep the function on the stack in a known slot, and use lua_pushvalue() to access it. That is quite a common situation.

If you are loading the function and then wish it to be called from inside the Lua script, you might as well make it a global. But I don't think that's your case.

If you are loading the function and then wish it to be called from a C function exported into a Lua script, then your best bet is to bind it to the C function as an upvalue.