Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance for table length operator

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.)

like image 937
charmlessCoin Avatar asked Dec 16 '22 07:12

charmlessCoin


1 Answers

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.

like image 182
lhf Avatar answered Jan 05 '23 17:01

lhf