table.remove performs better than using 2 manual assignments.
While running performance tests to compare some table-removal loop cases, I ran into a very peculiar find.
I have a large table being iterated over multiple times a second, and at any point during my loop I may need to remove the element at my current index, within the following criteria:
- The table may have it's order changed.
- The table may not have any nil-holes.
Using table.remove would satisfy the latter condition, as it shifts all elements above the removed one down to not leave any gaps.
However, since re-ordering is allowed, I thought I came up with a faster solution.
1. Set t[i] to the last element overriding and hence removing the element at the current index.
2. Set t[#] to nil, removing the last element that just got moved down, to not have any duplication.
I went on to test a few slightly different implementations of this:
1. Performing each assignment separately.
2. Performing both assignments in one go.
3. Same as the above but while saving #t to a local variable before doing so, avoiding the need to look it up twice.
Those 3 cases behaved as I expected them to. Performing from worst-to-best in the same order I just wrote them in. (Although, with minor difference.)
I did also test table.remove for comparison.
Surprisingly enough, that not only performed the best, but by a long-shot!
Sure, table.remove might (I have no clue) be implemented natively in C or what not, but still; how can shifting down all elements take less time than merely performing 2 assignments?!
Attached to this, is the repl where I did it, if you want to play around with it.
If anyone has an explanation for this, please do share; I am very intrigued.
Tests were run using Lua 5.1 with Love2D used to access a high-precision timer.
Edit: Mistakes were made. See my reddit post's comments for spoilers.
when i saw this i was like "finally another love2d user!" then went "oh" like really fast, really interesting though
@kwe I actually am! Love2D is my favorite framework, actually. I've been using it for a few years now, I'm working on my own rapid-dev-style engine inside it; and to top things off, I actually ran into this thing while I was working on a natural selection simulator made with Love2D.