function test() { console.log(arguments[arguments.length - 1]); }
var using = (new Array(200)).fill(null).map((e, i) => (i));
test(using);
test.apply(null, using)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
spread | |
apply |
Test name | Executions per second |
---|---|
spread | 142904.4 Ops/sec |
apply | 420610.4 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Overview
The benchmark is designed to compare two ways of calling a function with arbitrary arguments dynamically: using the spread operator (...
) and apply()
. The goal is to determine which approach is faster.
Script Preparation Code
The script preparation code defines a simple function test()
that takes an array of arguments as input. It then uses the spread operator to extract the last argument from the array, or apply()
with null
as the context and the using
array as the arguments.
function test() { console.log(arguments[arguments.length - 1]); }
var using = (new Array(200)).fill(null).map((e, i) => (i));
The using
array is created by mapping over an array of 200 elements with values from 0 to 199. This creates a large array that will be passed as arguments to the test()
function.
Test Cases
There are two test cases:
: This test case uses the spread operator (
...) to call the
test()function with the
using` array as arguments.: This test case uses
apply()to call the
test()function with
nullas the context and the
using` array as arguments.Library Used
None, this benchmark does not rely on any external libraries.
Special JS Feature/Syntax
The spread operator (...
) is a feature introduced in ECMAScript 2015. It allows you to pass an array of values as separate arguments to a function.
Pros and Cons of Different Approaches
...
):apply()
, especially for large arrays.apply()
:Other Considerations
When considering this benchmark, keep in mind that:
using
array (200 elements) is significant, which may impact performance differences between the two approaches.Alternatives
Other alternatives to compare in a similar benchmark could be:
apply()
, you could use destructuring assignment to extract the arguments from the array.rest parameter
syntax: You could use the rest parameter syntax (...args
) instead of the spread operator, which might offer better performance for large arrays.To prepare a similar benchmark, you would need to:
apply()
, spread operator, destructuring assignment, rest parameter syntax) to call the function and compare their performance.By running such benchmarks, you can gain insights into the performance characteristics of different JavaScript features and writing styles.