Why is [] .concat () faster than Array.prototype.concat ()?

I tested various methods of concatenating arrays not because it really matters for my code, but simply as an aside to see where we are now. As expected, the very new ES 2015 distribution operator is beaten by the old method concat()on Javascript arrays by a wide margin.

However, that surprised me a bit when I compared these two:

var a = b = c = [1,2,3,4,5];

// SLOWER (V8 and Edge, very slightly faster in Firefox)
console.time('t1');
for (i = 0; i < 1000000; i++) {
  Array.prototype.concat(a, b, c);
};
console.timeEnd('t1')

// FASTER (V8 and Edge, very slightly slower in Firefox)
console.time('t2');
for (i = 0; i < 1000000; i++) {
  [].concat(a, b, c);
};
console.timeEnd('t2')
Run code

, , node.js, Chrome Edge. V8 (node.js, Chrome) , Edge - V8 - . Firefox , , (V8 Chakra).

, , ,

1) , - ?

2) AFAICS () , ( ) ?

: , , () . , , : V8 (Chrome node.js) Microsoft Edge, ) .

, 4 downvotes ": " (!) . , , 2 , . . .

+4
1

Array.prototype.concat . , . .

var a = b = c = [1,2,3,4,5];

// Array.prototype.concat
console.time('t1');
var apc = Array.prototype.concat;
for (i = 0; i < 1000000; i++) {
  apc.call([], a, b, c);
};
console.timeEnd('t1')

// [].concat
console.time('t2');
for (i = 0; i < 1000000; i++) {
  [].concat(a, b, c);
};
console.timeEnd('t2')

// They're the same:
console.log(Array.prototype.concat === [].concat);

, (, ).

+7

Source: https://habr.com/ru/post/1654697/


All Articles