just learned a neat trick from the Three.js source code: if you want to remove an item from an array whose order doesn't matter, don't do this... array.splice(index, 1); // slooooowwwww ...do this: array[i] = array[array.length - 1]; array.pop(); // orders of magnitude faster!
-
Show this thread
-
Replying to @Rich_Harris
It becomes apparent why when you consider what splice does under the hood. All items after the removed one have to be shifted in memory to keep the array contiguous. This is O(n) — a linear operation, while swap/pop is O(1) — constant.
2 replies 0 retweets 16 likes -
Replying to @mourner @Rich_Harris
But V8 supports holey arrays, why the need to shift elements to keep the array contiguous? AFAIK V8 doesn't try to optimize the array contents when something like this happens. Maybe
@mathias can shed some light to it?2 replies 0 retweets 0 likes -
What it might happen is that removing the last element of an array doesn't really change the type of array but removing an arbitrary element from an array changes it to a holey one, making everything more expensive
1 reply 0 retweets 0 likes -
No, removing an item does not make a non-holey array holey (that would be pretty bad for performance). Looking at the splice source in v8, it does seem to move all items after the deleted one to shrink the array: https://github.com/v8/v8/blob/master/src/builtins/array-splice.tq#L54 …
1 reply 0 retweets 1 like
I mean, it does become holey if you use `delete`, so it was not an unreasonable assumption.
Loading seems to be taking a while.
Twitter may be over capacity or experiencing a momentary hiccup. Try again or visit Twitter Status for more information.
JavaScript, HTML, CSS, HTTP, performance, security, Bash, Unicode, i18n, macOS.