In programming languages like Scala or Lua, we can define nested functions such as
function factorial(n)
function _fac(n, acc)
if n == 0 then
return
Let's benchmark it in Lua with/without nested functions.
Variant 1 (inner function object is created on every call)
local function factorial1(n)
local function _fac1(n, acc)
if n == 0 then
return acc
else
return _fac1(n-1, acc * n)
end
end
return _fac1(n, 1)
end
Variant 2 (functions are not nested)
local function _fac2(n, acc)
if n == 0 then
return acc
else
return _fac2(n-1, acc * n)
end
end
local function factorial2(n)
return _fac2(n, 1)
end
Benchmarking code (calculate 12!
10 mln times and display used CPU time in seconds):
local N = 1e7
local start_time = os.clock()
for j = 1, N do
factorial1(12)
end
print("CPU time of factorial1 = ", os.clock() - start_time)
local start_time = os.clock()
for j = 1, N do
factorial2(12)
end
print("CPU time of factorial2 = ", os.clock() - start_time)
Output for Lua 5.3 (interpreter)
CPU time of factorial1 = 8.237
CPU time of factorial2 = 6.074
Output for LuaJIT (JIT-compiler)
CPU time of factorial1 = 1.493
CPU time of factorial2 = 0.141