Performance for table length operator

Lua has a # operator to calculate the "length" of the table used as an array. In a language such as C, after you have calculated the length of something, you usually do not calculate it again. for example int len = strlen(string);

Is this something else in Lua? Is less effective than another?

(Obviously, this probably won't show a noticeable difference for fairly small tables, but it never knows badly.)

+4
source share
1 answer

The # value for the table is not stored inside Lua: it is evaluated every time it is called.

Lua uses binary search, so the cost is logarithmic in the size of the table. See the code http://www.lua.org/source/5.2/ltable.c.html#luaH_getn . In other words, the cost is essentially constant, with the exception of huge tables.

+9
source

Source: https://habr.com/ru/post/1496709/


All Articles