sort string[] ASC vs. object with attr1 string then attr2 number ASC

Benchmark created on


Setup

/** @type {(l: number) => string} */
function createRandomString (l) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_!&$=/#'

  const res = []

  for (let i = 0; i < l; i += 1) {
    res.push(chars.charAt(Math.floor(Math.random() * chars.length)))
  }

  return res.join('')
}

/** @type {(_: { min: number, max: number }) => number} */
function getRandomNumber (_) {
  return (Math.random() * (_.max - _.min)) + _.min
}

const a = []
const b = []

for (let i = 0; i < 1e6; i += 1) {
  const o = { csn: createRandomString(16), dateMs: getRandomNumber({ min: 1e13, max: 2e13 }) }
  b.push(o)
  a.push([o.csn, o.dateMs].join('§'))
}

Test runner

Ready to run.

Testing in
TestOps/sec
sort string[] ASC
a.sort()
ready
sort attr1 string then attr2 number ASC
b.sort((a, b) => {
  let res = 0

  const csnA = a.csn
  const csnB = b.csn
  const bCsnDiff = csnA !== csnB

  if (bCsnDiff) {
    res = (csnA < csnB) ? -1 : 1
  } else {
    res = a.dateA - b.dateB
  }

  return res
})
ready

Revisions

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