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
}
}
const sorted = tmp.subarray(0, n).sort()
while (n--) {
let store = map.get(sorted[n])
while (store) {
res[--j] = store[0]
store = store[1]
}
}
return res
}
const sortMap3 = (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 arr = map.get(v)
if (arr === undefined) {
map.set(v, [item])
tmp[n++] = v
} else {
arr.push(item)
}
} else {
res[--j] = item
}
}
const sorted = tmp.subarray(0, n).sort()
while (n--) {
const arr = map.get(sorted[n])
let k = arr.length
while (k--) {
res[--j] = arr[k]
}
}
return res
}
Ready to run.
Test | Ops/sec | |
---|---|---|
native sort |
| ready |
native toSorted |
| ready |
sortSmart |
| ready |
sortMap |
| ready |
sortMap2 |
| ready |
sortMap3 |
| ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.