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 counter = 0
var f0 = wrap(function() { return counter++ })
var f1 = wrap(function(a) { return (counter += a) })
var f2 = wrap(function(a, b) { return (counter += (a + b)) })
var f3 = wrap(function(a, b, c) { return (counter += (a + b + c)) })
var f4 = wrap(function(a, b, c, d) { return (counter += (a + b + c + d)) })
var f5 = wrap(function(a, b, c, d, e) { return (counter += (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 | 2810095.5 Ops/sec |
With 1 parameter | 445385.5 Ops/sec |
With 2 parameters | 216158.5 Ops/sec |
With 3 parameters | 146745.9 Ops/sec |
With 4 parameters | 31633.5 Ops/sec |
With 5 parameters | 2730.4 Ops/sec |
Let's break down what's being tested in the provided JSON.
Benchmark Definition
The benchmark measures the performance of JavaScript functions with different numbers of arguments using two approaches:
wrap
function: This is a custom wrapper function created by MeasureThat.net to handle the creation and execution of the benchmarked functions.apply()
method or direct function invocation (fn()
, f0()
, etc.).Options being compared
The benchmark compares the performance of:
fn()
)apply()
method (fn.apply(this)
)wrap
function with different numbers of arguments (from 0 to 5)Pros and Cons of each approach:
fn()
)apply()
method (fn.apply(this)
)wrap
functionSpecial considerations
The benchmark uses some special JavaScript features, such as:
Date.now
to create a timestamp value that can be passed as an argumentwith
statement is not used in this case, but it's worth noting that it can be used to create a new scope and execute code within it.Other alternatives
If you're interested in alternative approaches for handling functions with a variable number of arguments, some options include:
Keep in mind that the performance characteristics of each approach may vary depending on the specific use case and requirements.