5

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

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
charmlessCoin
  • 754
  • 3
  • 13

1 Answers1

13

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.

lhf
  • 70,581
  • 9
  • 108
  • 149