Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why is table.getn(table) faster than #table?

t=tick()
print(#{"value1","value2"})
print(tick()-t) -- prints 0.0003

,

t=tick()
print(table.getn({"value1","value2"}))
print(tick()-t) -- prints 0.0001

numbers vary, but usually the first one is slower :/

3 comments

0

Oh boy, you really love these sorts of questions huh? You'll get better answers on a Lua forum (or even the Developer Forum); I'll wager that it has to do with a difference in algorithm, maybe #table checks which table[n+1] is nil and table.getn counts it using a loop.

0

maybe

0

actually, thats not it. i think they use the same way of counting values, using for loops in dictionaries to get number of items in it returns the number of the values, if you use table.getn() or # it returns 0

1 answer

✓ Accepted answer

Well, you're actually wrong.

The length operator uses the same baseline as table.getn() (which is deprecated btw), but the difference is calling its base function. Calling the function explicitly, as in table.getn(), is faster than calling the operator associated with that function, #. Lua is required to translate the operator into the purpose of the function, and therefore takes slightly longer to load # as opposed to table.getn().

In fact, Lua is super weird about numerous other things regarding code performance. For example, this...

t = {}
t[1] = 4
t[#t + 1] = 6

...is faster than this...

t = {}
t[1] = 4
table.insert(t, 6)

I'm not entirely certain why this happens, but it's most likely an issue with the code behind the function.

3 comments

0

and talbe.getn s deprecated?

0

table.getn() is deprecated

0

oh

This discussion is preserved as it was. New answers, comments, and votes are closed.