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
const error = type => {
throw new TypeError(`singledispatch not implemented for type ${type.constructor.name}`)
}
// Create a generic function that dispatches on the first argument.
// Returns a wrapped function that calls `defun`.
//
// Custom implementations for specific types can be registered through calling
// `.register(constructor, fun)` on the wrapped function.
//
// The default implementation is also exposed at `.default` on the wrapped
// function.
const singledispatch = (defun=error) => {
let key = Symbol('singledispatch')
const dispatch = (subject, ...rest) => {
let fun = subject[key]
if (fun) {
return fun(subject, ...rest)
}
return defun(subject, ...rest)
}
dispatch.default = defun
const register = (constructor, fun) => {
constructor.prototype[key] = fun
}
dispatch.register = register
return dispatch
}
class Foo {
constructor(x) {
this.x = x
}
add(y) {
return this.x + y
}
}
let add = singledispatch()
add.register(Foo, (foo, y) => foo.x + y)
const fadd = (x, y) => x + y
let foo = new Foo(2)
Ready to run.
Test | Ops/sec | |
---|---|---|
Plain function |
| ready |
Classical dispatch |
| ready |
Single dispatch |
| ready |
You can edit these tests or add more tests to this page by appending /edit to the URL.