Home > Back-end >  LUA: performance/efficiency of chaining functions
LUA: performance/efficiency of chaining functions

Time:12-11

I was always under the impression that chaining functions in LUA (version 5.1) would perform worse than localizing it first and then calling the next function.

Am I just wrong or is my simple benchmark incorrect?

local clock = os.clock
local plugin = {}

function plugin:Test()
    return { SubTest = function() return "hello" end }
end

collectgarbage(); collectgarbage()
local start = clock()
for i=1, 1000000 do
    plugin:Test():SubTest()
end
print(clock() - start, collectgarbage("count") / 1024)

collectgarbage(); collectgarbage()
local start = clock()
for i=1, 1000000 do
    local module = plugin:Test()
    module:SubTest()
end
print(clock() - start, collectgarbage("count") / 1024)

CodePudding user response:

chaining functions in LUA would perform worse than localizing it first and then calling the next function

That's true only if you use the local (cached) value multiple times.

is my simple benchmark incorrect?

Both loops in your benchmark get compiled to (almost) identical Lua bytecodes, so their performance must be equal.

  • Related