Most efficient way to determine if a Lua table is empty (contains no entries)?
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.)
better to avoid the evaluation of __eq if overloaded.
if rawequal(next(myTable), nil) then
-- myTable is empty
end
or
if type(next(myTable)) == "nil" then
-- myTable is empty
end
One possibility would be to count the number of elements, by using the metatable "newindex" key. When assigning something not nil
, increment the counter (the counter could live in the metatable as well) and when assigning nil
, decrement the counter.
Testing for empty table would be to test the counter with 0.
Here's a pointer to metatable documentation
I do like your solution though, and I honestly can't assume that my solution is faster overall.