开发者

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

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 s开发者_开发问答ome 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.


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.


p[#p] = nil will be faster, and identical for the case where table.remove is the last position

As an extra note, table.remove(func_call()) may do unexpected things if the function call returns multiple values.


Going from the implementation of the Lua 5.1 VM as described in Lua Performance Tips by Roberto Ierusalimschy (chief architect of Lua), the table's allocated storage doesn't change until the next time the table is rehashed - and, as stated time and time again, you really shouldn't be thinking about this unless you have hard profiling data showing it's a significant problem.

As for the difference between table.remove(t) and t[#t] = nil, see my answer to What's the difference between `table.insert(t, i)` and `t[#t+1] = i`.


I think it is better to be consistent with adding are removing elements from array type tables. table.insert and table.remove make your code consistent and easier to read.

Re: tables Lua doesn't resize the table until you have added the first new element to it after having previously removed elements.


table.remove(p) returns the value that was removed. p[#p] = nil does not return anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜