sort (v3)

Revision 3 of this benchmark created on


Setup

const items = Array.from({ length: 1e3 }).map(() => {
  const age = Math.floor(Math.random() * 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 sortCopyByNumberMap = (items, key) => {
  let i = items.length
  let j = 0
  let k = i
  const tmp = new Float64Array(i)
  const map = new Map()
  const res = Array(i)

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

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

  return res
}

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

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

  const sorted = tmp.subarray(0, j).sort()
  while (j--) {
    const arr = map.get(sorted[j])
    let l = arr.length
    while (l--) {
      res[--k] = 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
sortCopyByNumberMap
const sorted = sortCopyByNumberMap(items, 'age')
ready
sortCopyByNumberMap2
const sorted = sortCopyByNumberMap2(items, 'age')
ready

Revisions

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