function wrap(fn) {
// fast path if arity < 4, slow path if not
switch (fn.length) {
case 0:
return function() {
return fn.call(this)
}
case 1:
return function() {
return fn.call(this, this)
}
case 2:
return function(a1) {
return fn.call(this, this, a1)
}
case 3:
return function(a1, a2) {
return fn.call(this, this, a1, a2)
}
case 4:
return function(a1, a2, a3) {
return fn.call(this, this, a1, a2, a3)
}
default:
return function() {
const args = [this]
for (let i = 0, len = arguments.length; i < len; i++) {
args[i + 1] = arguments[i]
}
return fn.apply(this, args)
}
}
}
var f0 = wrap(function() { console.log(Date.now()) })
var f1 = wrap(function(a) { console.log(Date.now(), a) })
var f2 = wrap(function(a, b) { console.log(Date.now(), a, b) })
var f3 = wrap(function(a, b, c) { console.log(Date.now(), a, b, c) })
var f4 = wrap(function(a, b, c, d) { console.log(Date.now(), a, b, c, d) })
var f5 = wrap(function(a, b, c, d, e) { console.log(Date.now(), a, b, c, d, e) })
f0()
f1(Date.now)
f2(Date.now, Date.now + 1)
f3(Date.now, Date.now + 1, Date.now + 2)
f4(Date.now, Date.now + 1, Date.now + 2, Date.now + 3)
f5(Date.now, Date.now + 1, Date.now + 2, Date.now + 3, Date.now + 4)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
With 0 parameter | |
With 1 parameter | |
With 2 parameters | |
With 3 parameters | |
With 4 parameters | |
With 5 parameters |
Test name | Executions per second |
---|---|
With 0 parameter | 34706.9 Ops/sec |
With 1 parameter | 34291.7 Ops/sec |
With 2 parameters | 29877.6 Ops/sec |
With 3 parameters | 29267.1 Ops/sec |
With 4 parameters | 22543.0 Ops/sec |
With 5 parameters | 22863.7 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of different approaches to calling functions with varying numbers of arguments in JavaScript. The benchmark uses a custom function wrap
that wraps around the original function and determines which approach is faster based on the number of arguments.
Test Cases
There are six test cases:
Date.now
.Date.now
and Date.now + 1
.Date.now
, Date.now + 1
, and Date.now + 2
.Date.now
, Date.now + 1
, Date.now + 2
, and Date.now + 3
.Date.now
, Date.now + 1
, Date.now + 2
, Date.now + 3
, and Date.now + 4
.Approaches Compared
The benchmark compares two approaches:
fn.apply(this, args)
to call the function.Pros and Cons
fn.apply
.Library and Special Features
The benchmark uses no external libraries. However, it relies on JavaScript's built-in Date
object to generate argument values for each test case.
No special features are required to run this benchmark.
Interpretation of Results
The results show the execution speed of each approach for each test case, measured in executions per second (EPS). The fastest approach is usually the fast path, but there may be exceptions for functions with more than 4 arguments.