Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is table.remove() the same as p[#p] = nil and which is quicker?

Tags:

lua

As the title says. If I have a table p in lua, is using

table.remove(p)

the same as

p[#p] = nil

if so which is quicker - I'd guess the second, but would like some reassurance.

By the 'same as' I mean does the internal array storage shrink using assignment to nil? I can't seem to find this documented anywhere. Does setting the last element in an array to nil, or the last 10 elements in an array to nil mean the array will be shrunk, or does it always keep the storage and never shrink the array again?

I've assumed the array is contiguous, i.e. it has values stored in each array entry up to #p.

like image 934
daven11 Avatar asked Aug 20 '11 02:08

daven11


1 Answers

Setting the last element to nil will not be a function call. So in that way, it will certainly be faster than table.remove. How much that matters is up to you.

By the 'same as' I mean does the internal array storage shrink using assignment to nil? I can't seem to find this documented anywhere.

It isn't documented; this allows the implementation to change. All that Lua promises is that setting it to nil will decrease the size returned by subsequent calls to #p. Anything more than that is up to Lua, and is certainly subject to change without warning. It's nothing you should rely on.

However, I would respectfully suggest that if you're thinking about these kinds of micro-optimizations, you probably shouldn't be using a scripting language. A scripting language should be used for code where performance is not important enough to spend a great deal on.

like image 161
Nicol Bolas Avatar answered Dec 22 '22 11:12

Nicol Bolas