Array.prototype.sort vs customSort

Benchmark created on


Setup

const arr = [];
for (let i = 0; i < 10000; i++) {
	arr.push(Math.random());
}

function customSort(arr, callback) {
	if (arr.length < 1) {
		return arr;
	}

	if (arr.length === 2) {
		const compared = callback === undefined ? String(arr[0]) > String(arr[1]) : callback(arr[0], arr[1]);
		if (compared === 0 || compared < 0) {
			return arr;
		} else {
			return [arr[1], arr[0]];
		}
	}
	
	return arr.sort(callback);
}

function nativeSort(arr, callback) {	
	return arr.sort();
}

function compare(a, b) {
	return a - b;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Array.prototype.sort
nativeSort(arr);
nativeSort([]);
nativeSort([123]);
nativeSort([123, 124]);
nativeSort([124, 123]);
nativeSort(arr, compare);
nativeSort([], compare);
nativeSort([123], compare);
nativeSort([123, 124], compare);
nativeSort([124, 123], compare);
ready
customSort
customSort(arr);
customSort([]);
customSort([123]);
customSort([123, 124]);
customSort([124, 123]);
customSort(arr, compare);
customSort([], compare);
customSort([123], compare);
customSort([123, 124], compare);
customSort([124, 123], compare);
ready

Revisions

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