window.testArray = [1, 'a', undefined, null, false, { a: 123 }, [1, 2, 3]];
window.arraySlice = Array.prototype.slice;
window.arrayConcat = Array.prototype.concat;
const a = window.testArray.slice();
const a = arraySlice.call(window.testArray);
const a = window.testArray.concat([]);
const a = window.arrayConcat.call(window.testArray, []);
const a = [window.testArray];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.prototype.slice [direct call] | |
Array.prototype.slice [saved function call] | |
Array.prototype.concat [direct call] | |
Array.prototype.concat [saved function call] | |
Spread operator |
Test name | Executions per second |
---|---|
Array.prototype.slice [direct call] | 6305539.0 Ops/sec |
Array.prototype.slice [saved function call] | 3341683.5 Ops/sec |
Array.prototype.concat [direct call] | 3928783.0 Ops/sec |
Array.prototype.concat [saved function call] | 2555343.2 Ops/sec |
Spread operator | 6121413.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition
The provided JSON defines a benchmark that compares three ways to create an array in JavaScript: Array.slice()
, Array.concat()
, and the spread operator (...
). The benchmark is designed to measure the performance of each approach.
Options Compared
Here are the options being compared:
slice()
method directly on the Array
prototype.slice()
method in a variable (arraySlice
) and calling it using the saved reference....
) to create an array.Pros and Cons
Here's a brief summary of each approach:
Library Usage
None of the benchmark tests use any external libraries.
Special JS Features or Syntax
The test cases don't explicitly use any special JavaScript features or syntax. However, it's worth noting that the spread operator (...
) was introduced in ECMAScript 2015 (ES6) and has become a widely supported feature across modern browsers.
Benchmark Preparation Code
The provided preparation code sets up the testArray
variable with a mix of primitive values and objects, which is used to test the different array creation approaches. The arraySlice
and arrayConcat
variables are assigned references to the slice()
and concat()
methods on the Array
prototype.
Benchmark Results
The latest benchmark results show that:
Keep in mind that these results may vary depending on the specific browser, device platform, and operating system used to run the benchmark.
Other Alternatives
If you're interested in exploring alternative methods for creating arrays in JavaScript, here are a few options:
Array.from()
: This method creates an array from an iterable source, such as an array or string.Array.isArray()
**: This method checks whether an object is an array.new Array()
: This method creates a new empty array.These alternatives may offer different performance profiles or use cases, depending on the specific requirements of your project.