charmlessCoin
charmlessCoin

Reputation: 774

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

Upvotes: 6

Views: 2014

Answers (1)

lhf
lhf

Reputation: 72392

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.

Upvotes: 14

Related Questions