4 ms·
> Invoking Array(length) or new Array(length) (with a number argument) creates a fully sparse array: In my experience the common javascript engines are so acce
by strainer 5y ago
> Invoking Array(length) or new Array(length) (with a number argument) creates a fully sparse array:
In my experience the common javascript engines are so accelerated that in practice, before anything happens to the array it is uninitialised and the engine uses the length parameter as a future hint. If the array is promptly filled contiguously it will perform as a dense array.
The types which the array is filled with and subsequently maintains can have a greater impact on performance. An array that only contains integers performs faster than one containing doubles or strings, and once types are changed or mixed in the array it slows down, generally by a factor of 2 or 3.
- zodiakzz 5y agoCan you provide a source on that? Coz the v8 blog has like a monthly dedicated warning post against the dreaded "Holey" array and how it's the archnemesis of all performance optimizations. Ok exaggeration aside, it's something along the lines of "A holey array will never _ever_ become packed...".
- eyelidlessness 5y agoDoes that mean this: Array(n).fill() is a permanent deoptimization? And if so, is the new array returned by: Array(n).fill().map(x => x) better optimized (after the, presumably, suboptimal iteration)?
- strainer 5y agoJust many hours of time micro-optimising quirky projects like [1]. I could write a test specifically to demonstrate it... and write a little article... but just commenting here that in my humdrum experience - you might want to look into it yourself. I have tested and never seen any benefit in eg. initializing an array as [0,0,0,0,0,0,0,0,0,0,0,0,0,0,...] compared to Array(n) for (i=0;i<n; i++) A[i]=0 ... Ymmv. Takes moments to check with a benchmarking package of choice. I recommend avoiding testing it with any functional kind of expressions though, because they can be much slower than the old imperative style and obscure the picture. ...also, from a reasoning approach - why would a competitively accelerated language engine create an array full of holes as soon as one is declared? Why would the engine not try to optimally structure the type as it is used? This is something Chromes engines and Firefoxes appear to have done, quite impressively since many years back. [1] https://github.com/strainer/fencache.js https://github.com/strainer/fencache.js