Tomarty
(Tomarty)
April 25, 2020, 9:34pm
12
Here’s a related reply from @zeuxcg :
If the table doesn’t reallocate then it’s indeed faster to “cache” the table length as you do right now. Computing the length is not free - it’s very cheap for “proper” arrays with exact size but gets expensive when arrays get reallocated. I’ll spare the details but it can take time, e.g. in one of our benchmarks that tested array assignment performance, we had to change a loop like this
for i=1,N do t[#t+1] = i end
to a loop like this:
for i=1,N do t[i] = i end
to make sure the extra overhead of #
didn’t “pollute” the benchmark numbers.
I have a dream to fix this but it involves doing a deep semantical change to how Lua tables/arrays behave with length. It will have compatibility issues, and I’m not sure we’ll be able to deploy it safely (this is because it would change the semantics of #
operator on tables with holes)
If you really need to track the length of an array with holes, you should probably store it yourself instead of using #
, as the behavior is somewhat undefined. The implementation is a balance between performance and consistency.
2 Likes