sort

Benchmark created on


Setup

const items = Array.from({ length: 100e3 }).map(() => {
  const age = Math.floor(Math.random() * 4294967295)
  return {
    age,
    name: 'Youzi ' + age,
  }
})

const coolsortIndex = (items, key, Arr) => {
  let i = items.length
  let j = 0
  const map = {}
  const res = Array(i)
  const tmp = new Arr(i)

  // count first
  while (i--) {
    const v = items[i][key]
    if (v in map) {
      map[v].push(i)
    } else {
      tmp[j] = v
      map[v] = [i]
      j++
    }
  }

  // sort the values
  const srt = tmp.subarray(0, j).sort()
  for (const v of srt) {
    for (const idx of map[v]) {
      res[++i] = items[idx]
    }
  }

  return res
}

const coolsortRef = (items, key, Arr) => {
  let i = items.length
  let j = 0
  const map = {}
  const res = Array(i)
  const tmp = new Arr(i)

  // count first
  while (i--) {
    const item = items[i]
    const v = item[key]
    if (v in map) {
      map[v].push(item)
    } else {
      tmp[j] = v
      map[v] = [item]
      j++
    }
  }

  // sort the values
  const srt = tmp.subarray(0, j).sort()
  for (const v of srt) {
    for (const item of map[v]) {
      res[++i] = item
    }
  }

  return res
}

const coolsortRef2 = (items, key, Arr) => {
  let i = items.length
  let j = 0
  const map = {}
  const res = Array(i)
  const tmp = new Arr(i)

  // count first
  while (i--) {
    const item = items[i]
    const v = item[key]
    if (v in map) {
      map[v].push(item)
    } else {
      tmp[j] = v
      map[v] = [item]
      j++
    }
  }

  // sort the values
  const srt = tmp.subarray(0, j).sort()
  for (const v of srt) {
    let k = map[v].length
    while (k--) {
      res[++i] = map[v][k]
    }
  }

  return res
}

Test runner

Ready to run.

Testing in
TestOps/sec
coolsortIndex
const sorted = coolsortIndex(items, 'age', Uint32Array)
ready
coolsortRef2
const sorted = coolsortRef2(items, 'age', Uint32Array)
ready
coolsortRef
const sorted = coolsortRef(items, 'age', Uint32Array)
ready

Revisions

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