jsPerf.app is an online JavaScript performance benchmark test runner & jsperf.com mirror. It is a complete rewrite in homage to the once excellent jsperf.com now with hopefully a more modern & maintainable codebase.
jsperf.com URLs are mirrored at the same path, e.g:
https://jsperf.com/negative-modulo/2
Can be accessed at:
https://jsperf.app/negative-modulo/2
Sort by number (without mutation)
const items = Array.from({ length: 1e3 }).map((_, index) => {
const publishedAt = Math.floor(Math.random() * Date.now())
return {
publishedAt,
name: 'Article ' + index }
})
const sortMap = (items, key) => {
const l = items.length
const tmp = new Float64Array(l)
const res = Array(l)
const map = new Map()
let i = l
let j = l
while (i--) {
const item = items[i]
const v = item[key]
if (typeof v === 'number') {
const k = v * l + i
map.set(k, item)
tmp[i] = k
} else {
res[--j] = item
}
}
const sorted = tmp.subarray(0, j).sort()
while (j--) {
res[j] = map.get(sorted[j])
}
return res
}
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
}
const sortMap2 = (items, key) => {
const l = items.length
const tmp = new Float64Array(l)
const res = Array(l)
const map = new Map()
let i = l
let j = l
let n = 0
while (i--) {
const item = items[i]
const v = item[key]
if (typeof v === 'number') {
const store = map.get(v)
if (store === undefined) {
map.set(v, [item])
tmp[n++] = v
} else {
map.set(v, [item, store])
}
} else {
res[--j] = item
}
}
let k = l - n
const sorted = tmp.subarray(0, k).sort()
while (k--) {
let store = map.get(sorted[k])
while (store) {
res[--j] = store[0]
store = store[1]
}
}
return res
}
Ready to run.
Test | Ops/sec | |
---|---|---|
native sort |
| ready |
native toSorted |
| ready |
sortSmart |
| ready |
sortMap |
| ready |
sortMap2 |
| ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.