What's the most efficient way to determine if a table is empty (that is, currently contains neither array-style values nor dict-style values)?
Currently, I'm using next()
:
if not next(myTable) then
-- Table is empty
end
Is there a more efficient way?
Note: The #
operator does not suffice here, as it only operates on the array-style values in the table - thus #{test=2}
is indistinguishable from #{}
because both return 0. Also note that checking if the table variable is nil
does not suffice as I am not looking for nil values, but rather tables with 0 entries (i.e. {}
).
Your code is efficient but wrong. (Consider {[false]=0}
.) The correct code is
if next(myTable) == nil then
-- myTable is empty
end
For maximum efficiency you'll want to bind next
to a local variable, e.g.,
...
local next = next
...
... if next(...) ...
(When next
is local, the code finds primitive function next
by a constant-time indexing operation into an array of "upvalues." When next
is left global, finding next
involves indexing index the "environment" hash table, which contains the values of the global variables. This indexing operation is still constant-time, but it is significantly slower than the array lookup for a local variable.)