[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Tail call benchmarks
- From: Wim Couwenberg <wim.couwenberg@...>
- Date: Mon, 23 Feb 2009 09:54:01 +0100
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
machine:
local function fac(n)
local r = 1
for i = 2, n do r = r*i end
return r
end
local function facr(n, r)
if n == 1 then return r end
return facr(n - 1, n*r)
end
local now = os.clock()
for i = 1, 1e6 do
local f = fac(20, 1) -- extra argument to have same call expression
end
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)
end
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.
Bye,
Wim
> │ "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.