Lua has the #
operator to compute the "length" of a table being used as an array. In a language such as C, after you've computed the length of something, you typically don't compute it again. e.g. int len = strlen(string);
Is this any different in Lua? Is one less efficient than the other?
(Obviously this probably won't show a noticeable difference for fairly small tables, but it's never bad to know.)
The value of #
for a table is not stored internally by Lua: it is computed every time it is called.
Lua uses a binary search and so the cost is logarithmic in the size of the table. See the code at http://www.lua.org/source/5.2/ltable.c.html#luaH_getn. In other words, the cost is essentially constant, except for huge tables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With