[SOLVED] LUA: performance/efficiency of chaining functions

Issue

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)

Solution

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.

Answered By – Egor Skriptunoff

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *