Why is concat slower than spread inside reduce and is faster otherwise?

  arrays, javascript, performance

SITUATION 1:

So, I’ve two arrays foo and bar. And I merge them into a single array using both concat and spread and it turns out that concat performs faster than spread.

const foo = Array.from({ length: 10000 }, () => ({
  num: Math.floor(Math.random() * 100),
}));

const bar = Array.from({ length: 10000 }, () => ({
  num: Math.floor(Math.random() * 100),
}));

function concat() {
  const startTime = performance.now();
  const res = foo.concat(bar)
  console.log("Concat:", performance.now() - startTime);
}

function spread() {
  const startTime = performance.now();
  const res = [...foo, ...bar]
  console.log("Spread:", performance.now() - startTime);
}

concat();
spread();

SITUATION 2:

This time I’ve only taken the array foo which is an array of objects like these {num: Math.floor(Math.random() * 100)}. I will reduce them into an array of numbers using both concat and spread, but this time spread is faster than concat, I want to know why is this happening?

const foo = Array.from({ length: 10000 }, () => ({
  num: Math.floor(Math.random() * 100),
}));

function concat() {
  const startTime = performance.now();
  const res = foo.reduce((res, num) => res.concat(num.num), []);
  console.log("Concat:", performance.now() - startTime);
}

function spread() {
  const startTime = performance.now();
  const res = foo.reduce((res, num) => [...res, num.num], []);
  console.log("Spread:", performance.now() - startTime);
}

concat();
spread();       

Source: Ask Javascript Questions

LEAVE A COMMENT