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
To be clear, holey arrays are still optimized! It’s just that their peak performance is not as amazing as packed arrays.
8:04 AM - 8 May 2019
0 replies
0 retweets
2 likes
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.