Sort by number (v10)

Revision 10 of this benchmark created on


Description

Sort by number (without mutation)

Setup

const items = Array.from({ length: 1e3 }).map((_, index) => {
	const publishedAt = Math.floor(Date.now() * Math.random())
  return {
    publishedAt,
    name: 'Article ' + index }
})

const sortSmart = (items, key) => {
  const l = items.length
  const b = 32 - Math.clz32(l)
  const x = 1 << b
  const m = x - 1
  const tmp = new Float64Array(l)
  const res = Array(l)
  let i = l
  let j = l
  while (i--) {
    const item = items[i]
    const v = item[key]
    if (typeof v === 'number') {
      tmp[i] = v * x + i
    } else {
      res[--j] = item
    }
  }
  const sorted = tmp.subarray(0, j).sort()
  while (j--) {
    res[j] = items[sorted[j] & m]
  }
  return res
}

Test runner

Ready to run.

Testing in
TestOps/sec
native sort
const sorted = Array.from(items).sort((a,b) => a.publishedAt - b.publishedAt)
ready
native toSorted
const sorted = items.toSorted((a,b) => a.publishedAt - b.publishedAt)
ready
sortSmart
const sorted = sortSmart(items, 'publishedAt')
ready

Revisions

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