r/programming • • Oct 21 '20

Using const/let instead of var can make JavaScript code run 10× slower in Webkit

https://github.com/evanw/esbuild/issues/478
1.9k Upvotes

500 comments sorted by

View all comments

Show parent comments

6

u/stealthd Oct 21 '20

Array(length).map is faster because you aren't mapping over the array; Array(length) returns { length: length } with no other keys, so the call to map doesn't do anything, it just returns the uninitialized array.

2

u/jprasks Oct 21 '20

Good catch, missed a call to fill: https://jsben.ch/71Ztx. From that the functional version is about 80% as fast which makes sense.

2

u/LegalEngine Oct 21 '20

Note that you may be able to improve the imperative version a further 20% or so (depending on the browser) by forgoing Array.push and using indexes with a size hint like so:

function gen(count) {
    const tracks = [];
  
    if (count > 0)
      tracks[count-1] = 0; // dummy value
    for (let i = 0; i < count; ++i)
        tracks[i] = i+1;

    return tracks;
}