sort speed difference

Benchmark created on


Description

testing speedup of using native sort functions vs manually sorting a very small array

Preparation HTML

<script>
function toSorteded(item) {
  const requiredSizes = [2.3, 2.3, 4];
  const providedSizes = [item.length, item.width, item.height].toSorted();
  return requiredSizes.every((e, i) => {return providedSizes.at(i) === e});
}

function insertionSorted(item) {
  const requiredSizes = [2.3, 2.3, 4];
  const providedSizes = [item.length, item.width, item.height];
  // insertion sort
  providedSizes.forEach((curr, i, a) => {
    if (i !== 0) {
      let end = i-1;
      while (end >= 0 && a.at(end) > curr) {
      	a[end + 1] = a[end];
      	--end;
      }
      a[end + 1] = curr;
    }
  });
  return requiredSizes.every((e, i) => {return providedSizes.at(i) === e});
}

function manualed(item) {
	function swap(arr, a, b) {
		let tmp = arr[a];
		arr[a] = arr[b];
		arr[b] = tmp;
	}
  const requiredSizes = [2.3, 2.3, 4];
  const providedSizes = [item.length, item.width, item.height];
  
  // [4, 2.3, 2.3]
  if (providedSizes.at(0) === 4) swap(providedSizes, 0, 2)
  // [2.3, 4, 2.3]
  else if (providedSizes.at(1) === 4) swap(providedSizes, 1, 2)
  return requiredSizes.every((e, i) => {return providedSizes.at(i) === e});
}

const a = {length: 4, width: 2.3, height: 2.3};
const b = {length: 2.3, width: 4, height: 2.3};
const c = {length: 2.3, width: 2.3, height: 4};
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
using toSorted()
toSorteded(a)
toSorteded(b)
toSorteded(c)
ready
insertion sort
insertionSorted(a)
insertionSorted(b)
insertionSorted(c)
ready
manually sorting
manualed(a)
manualed(b)
manualed(c)
ready

Revisions

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