[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to append argument(s) to ...?
- From: Dolphin <dhawkins@...>
- Date: Wed, 22 Apr 2009 14:44:12 +0000 (UTC)
Atry <pop.atry <at> gmail.com> writes:
>
> local function append(x, arg1, ...)
> if arg1 == nil then
> return x
> else
> return arg1, append(x, ...)
> end
> end
>
> local tinsert = table.insert
> local function append_t(x, ...)
> local t = {...}
> tinsert(t, x)
> return unpack(t)
> end
>
> do
> t = os.clock()
> for i = 1, 100000 do
> append_t(1,1,1,1,1)
> end
> print(os.clock() - t)
> end
>
> do
> t = os.clock()
> for i = 1, 100000 do
> append(1,1,1,1,1)
> end
> print(os.clock() - t)
> end
>
local function append3(x, arg1, ...)
if arg1 == nil then
return x
end
return arg1, append(x, ...)
end
This gets you one less JMP instruction in the function, and should be (ever so
slightly) faster.
The recursive version, in addition to being faster (for small numbers of
arguments) also creates much less garbage which may be important in a
constrained memory environment.
collectgarbage('collect')
collectgarbage('collect')
collectgarbage('collect')
do
local mem=collectgarbage('count')
collectgarbage('stop')
local t = os.uptime()
for i = 1, 100000 do
append_t(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
end
print(os.uptime() - t, collectgarbage('count')-mem)
collectgarbage('restart')
end
This reports over 100Mb of garbage created, while the recursive versions report
around 40k (and the amount of garbage does not increase with the number of times
through the loop)