sort (v2)

Revision 2 of this benchmark created on


Setup

const items = Array.from({ length: 100e3 }).map(() => {
  const age = Date.now()
  return {
    age,
    name: 'Youzi ' + age,
  }
})

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

  while (i--) {
    const item = items[i]
    const v = item[key]
    if (typeof v !== 'number') {
      res[--k] = item
    } else if (v in map) {
      map[v].push(item)
    } else {
      tmp[j] = v
      map[v] = [item]
      j++
    }
  }

  const sorted = tmp.subarray(0, j).sort()
  for (const v of sorted) {
    const arr = map[v]
    let l = arr.length
    while (l--) {
      res[++i] = arr[l]
    }
  }

  return res
}

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

  while (i--) {
    const item = items[i]
    const v = item[key]
    if (typeof v !== 'number') {
      res[--k] = item
    } else if (v in map) {
      map[v].push(item)
    } else {
      tmp[j] = v
      map[v] = [item]
      j++
    }
  }

  const sorted = tmp.subarray(0, j).sort()
  for (const v of sorted) {
    const arr = map[v]
    let l = arr.length
    while (l--) {
      res[++i] = arr[l]
    }
  }

  return res
}

Test runner

Ready to run.

Testing in
TestOps/sec
Array.from(items).sort(fn)
const sorted = Array.from(items).sort((a,b) => a.age === b.age ? 0 : a.age < b.age ? -1 : 1)
ready
sortCopyByNumber
const sorted = sortCopyByNumber(items, 'age')
ready
sortCopyByNumber2
const sorted = sortCopyByNumber2(items, 'age')
ready

Revisions

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