merge one array into another array (v10)

Revision 10 of this benchmark created on


Description

Like array.concat

https://x.com/rxdbjs/status/1808987298530537839

https://rxdb.info/

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 fillLastOne(arr, add){
  const addSize = add.length;
  if (addSize === 0) {
    return;
  }
  const baseSize = arr.length;
  arr.length = baseSize + addSize;
  arr[arr.length - 1] = add[0]
  for (let i = 0; i < addSize; i++) {
    arr[baseSize + i] = add[i];
  }
}

function flatten(arr, add){
	return [arr, add].flat();
}

function testData(amount){
	return new Array(amount).fill(0).map(() => {
		return {
			a: Math.random(),
			b: Math.random(),
			c: Math.random(),
			d: Math.random(),
			e: Math.random(),
			f: Math.random(),
			g: Math.random(),
			h: Math.random(),
		}
	})
}

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

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
concat
concat(ar.slice(0), add.slice(0))
ready
fillLastOne
fillLastOne(ar.slice(0), add.slice(0))
ready
flatten
flatten(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.