lua-users home
lua-l archive

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

Thanks for that.  I use tail recursion often, mostly to replace "for"
and "while" constructs though.  The code becomes more readable.
However, there is price to pay.  In the following example the tail
call version runs about 3.8 times slower than the "for" version on my

local function fac(n)
    local r = 1
    for i = 2, n do r = r*i end
    return r

local function facr(n, r)
    if n == 1 then return r end
    return facr(n - 1, n*r)

local now = os.clock()
for i = 1, 1e6 do
    local f = fac(20, 1)  -- extra argument to have same call expression
now = os.clock() - now
print(string.format("for version took %.3f sec", now))

now = os.clock()
for i = 1, 1e6 do
    local f = facr(20, 1)
now = os.clock() - now
print(string.format("tail call version took %.3f sec", now))

It would be great if tail calls could be made cheaper.


> │ "People who think they know everything really annoy those of us who
> │ know we don't." --- Bjarne Stroustrup

People who do not know themselves annoy me even more.