• Subject: Re: Returning nil vs returning nothing
• From: Andrew Gierth <andrew@...>
• Date: Thu, 29 Oct 2020 00:20:54 +0000

```>>>>> "Viacheslav" == Viacheslav Usov <via.usov@gmail.com> writes:

>> The examples that use pack/unpack seem misguided since they're
>> allocating a table unnecessarily.

Viacheslav> Speaking of my example, it answered the two questions
Viacheslav> above, not just the second one. PiL 3 recommends that
Viacheslav> tables are the general way to handle variadic arguments.
Viacheslav> There was a discussion and some benchmarking here four-five
Viacheslav> years ago, when it was found that one should worry about
Viacheslav> the impact of table creation only when the actual number of
Viacheslav> variadic arguments is 0, 1 or 2. With progressively more
Viacheslav> variadic arguments, they are first on par and then (vastly)
Viacheslav> better than other ways of handling variadic arguments.

Given:

local function foo1(f,...)
local function drop1(s,...)
if s then
return ...
else
return
end
end
drop1(f(...))
end

local function foo2(f,...)
local r = table.pack(f(...))
if r[1] then
return table.unpack(r, 2, r.n)
else
return
end
end

then averaged over a large number of calls, with 5 to 50 results in
the list, foo2 is around 3x slower than foo1. The proportional speed
difference does not seem to be narrowing for longer argument lists.
(For short lists the difference is narrower, but the non-table version
is always at least 2x faster.)

Now, for something other than "drop the first result" which happens to
be easy without needing a table, it might well be simpler to use a table
(dropping the last result, for example, would require a lot of
recursion).

--
Andrew.

```