var classes = document.body.querySelector('[class]').classList
var other = Array.prototype.slice.call(classes);
var other = [ classes ]
var other = [];
[].push.apply(other, classes)
var other = Array.from(classes);
var other = Object.values(classes);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
slice | |
spread operator | |
push apply into empty array | |
Array.from | |
Object.values |
Test name | Executions per second |
---|---|
slice | 256590.7 Ops/sec |
spread operator | 480849.5 Ops/sec |
push apply into empty array | 1147929.8 Ops/sec |
Array.from | 369462.1 Ops/sec |
Object.values | 124244.7 Ops/sec |
Overview of the Benchmark
The provided benchmark compares different approaches to convert an HTML class list to an array in JavaScript. The test cases use various methods, including Array.prototype.slice.call()
, spread operator (...
), push.apply()
into an empty array, Array.from()
, and Object.values()
. The goal is to determine which method is the most efficient.
Options Compared
The benchmark compares the following options:
Array.prototype.slice.call(classes)
: This method uses the slice()
method to extract a portion of the class list as an array, and then calls the call()
method to convert it into an actual array....
): This method uses the spread operator to create a new array from the class list.push.apply(other, classes)
: This method uses the apply()
method to call the push()
method on an empty array with the class list as its argument.Array.from(classes)
: This method uses the from()
method to create a new array from the class list.Object.values(classes)
: This method uses the values()
method to get a value iterator for the class list, and then converts it into an array.Pros and Cons of Each Approach
Array.prototype.slice.call(classes)
:...
):push.apply(other, classes)
:apply()
.Array.from(classes)
:Object.values(classes)
:Special Considerations
The benchmark uses the classList
property to access the class list of an HTML element. This is a common pattern in modern web development.
The test cases use different libraries and features that may affect the results, such as:
Chrome 66
: The browser version used for testing.Windows NT 10.0; Win64; x64
: The device platform and operating system used for testing.Other Alternatives
If none of these methods are suitable for your use case, you may consider using other approaches, such as:
In conclusion, the spread operator (...
) and Array.from(classes)
are likely to be the most efficient methods in modern browsers, while the other approaches may be less efficient or require additional libraries.