merge one array into another array (v4)

Revision 4 of this benchmark created on


Description

Like array.concat

Setup

function noConstVar(arr, add){
  const addSize = add.length;
  if (addSize === 0) {
    return;
  }
  const baseSize = arr.length;
  arr.length = baseSize + addSize;

  for (let i = 0; i < addSize; i++) {
    arr[baseSize + i] = add[i];
  }
}
function withConstVar(arr, add){
  const addSize = add.length;
  if (addSize === 0) {
    return;
  }
  const baseSize = arr.length;
  arr.length = baseSize + addSize;

  for (let i = 0; i < addSize; i++) {
  	const element = add[i]
    arr[baseSize + i] = element;
  }
}

function addFromBehind(arr, add){
      const addSize = add.length;
    if (addSize === 0) {
        return;
    }
    const baseSize = arr.length;
    arr.length = baseSize + addSize;
    const totalSize = baseSize + addSize;
    const maxIndex = totalSize - 1;
    let t = 0;
    for (let i = addSize - 1; i >= 0; i-- && t++) {
        arr[maxIndex - t] = add[i];
    }

}

function spreadOperator(arr, add){
  arr.push(...add);
}

function shift(arr, add){
    add = add.slice(0);
    while (true) {
        const x = add.shift();
        if (x) {
            arr.push(x)
        } else {
            return;
        }
    }
}

function concat(arr, add){
  return arr.concat(add);
}


function testData(amount){
	return new Array(amount).fill(0).map(() => {
		return {
			a: Math.random(),
			b: Math.random()
		}
	})
}

const ar = testData(80000);
const add = testData(80000);

Test runner

Ready to run.

Testing in
TestOps/sec
noConstVar
noConstVar(ar.slice(0),add.slice(0))
ready
withConstVar
withConstVar(ar.slice(0),add.slice(0))
ready
addFromBehind
addFromBehind(ar.slice(0),add.slice(0))
ready
spreadOperator
spreadOperator(ar.slice(0), add.slice(0))
ready
shift
shift(ar.slice(0), add.slice(0))
ready
concat
concat(ar.slice(0), add.slice(0))
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.