merge sorted arrays (v2)

Revision 2 of this benchmark created on


Setup

const ARR_LEN = 1000;
const arr1 = [...Array(ARR_LEN)].map((_, i) => i * 3);
const arr2 = [...Array(ARR_LEN)].map((_, i) => i * 7);

Test runner

Ready to run.

Testing in
TestOps/sec
es6
const merged = [...arr1, ...arr2].sort((a, b) => a - b);
ready
for
const merged = Array(arr1.length + arr2.length);
let i1 = 0, i2 = 0;
for (let j = 0; j < merged.length; j++) {
	if (arr1[i1] < arr2[i2]) {
		merged[j] = arr1[i1];
		i1++;
	}
	else {
		merged[j] = arr2[i2];
		i2++;
	}
}
ready
for optimized
const merged = Array(arr1.length + arr2.length);
let i1 = 0, i2 = 0;
for (let j = 0; j < merged.length; j++) {
		merged[j] = arr1[i1] < arr2[i2] ? arr1[i1++] : arr2[i2++];
}
ready
for optimized 2
const merged = Array(arr1.length + arr2.length);
for (let j = 0, i1 = 0, i2 = 0; j < merged.length; j++) {
		merged[j] = arr1[i1] < arr2[i2] ? arr1[i1++] : arr2[i2++];
}
ready
for optimized 3
const merged = Array();
for (let j = 0, i1 = 0, i2 = 0; i1 < arr1.length && i2 < arr2.length; j++) {
		merged.push(arr1[i1] < arr2[i2] ? arr1[i1++] : arr2[i2++]);
}
ready

Revisions

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