Question

I have the following function that simply returns its string argument:

function N_(s)
  return s
end

You may recognize this function name from gettext. It's a marking for the benefit of the .pot extractor only.

Would it be more efficient to implement N_() in C or in Lua?

Can you give me a rule of thumb?

Another question:

Let's say I have a function a bit more complicated:

function Z_(s)
  return dict[s] or s
end

Would it be more efficient to implement Z_() in C or in Lua?

(I'll be calling both N_() and Z_() from Lua code, not from C code.)

Was it helpful?

Solution 2

Functions implemented in Lua that aren't very processor-intensive are very likely to be more efficient than those in C, if you're spending most of your time in Lua. This is especially true if you end up using LuaJIT at some time in the future. The compiler will always be able to infer more information from your function if it's in the language than if it's some obscure C function which it doesn't know anything about, and it doesn't have to do as much hopping around different contexts.

The problem with implementing Z_ in C is that you would also have to implement dict in C, where Lua already has such functionality in place. So, it depends if you need some specially optimized hash map, maybe C would be better.


If your concern is about function call efficiency, why not just cache the results?

-- instead of doing:
print(Z_('Hello world! My name is %1!', 'Lua'))
-- perhaps do this:
local greeting = Z_('Hello world! My name is %1!', 'Lua')
print(greeting)
-- reuse greeting at some later time.

Of course, your Z_ function doesn't look like it takes substitutions yet, but I assume it might later. However, if you never need substitutions, you may as well make it a table like this:

local Z = setmetatable({}, {__index = function(t,k) return k end})
Z['greetings'] = 'Hello world!'
print(Z['greetings']) -- Hello world!
print(Z['goodbye']) -- goodbye

This table has an __index metamethod which returns the key used, if the table does not have such an entry.

OTHER TIPS

I haven’t measured the difference in this case but I expect writing it in Lua will be faster. Calling C functions is somewhat more expensive.

As a rule of thumb, write it all in Lua, unless it's a long task for which there exists a library C function.

Keep in mind that you'll probably be much more productive writing Lua code than C code. You're thus likely to get it right sooner in Lua. The performance will probably be good enough.

In all cases, YMMV and so measure it yourself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top