Home > Article > Web Front-end > Is `slice()` Still The Fastest Way to Convert a NodeList to an Array?
Converting JavaScript NodeList to Array: Speed Considerations
Previous discussions on the topic of converting NodeLists to arrays have claimed that using the slice() method is the most efficient approach. However, recent benchmarks have revealed a surprising finding.
Benchmark Observations
In experiments conducted on Chromium 6, it was discovered that creating an array from a NodeList using a simple for loop outperforms the slice() method by more than threefold. This result conflicts with earlier assertions regarding the superiority of slice().
Possible Explanations
The reason for this discrepancy may stem from browser-specific optimizations or differences in JavaScript engine implementations. It is possible that the Chromium engine handles the for loop more efficiently in this scenario.
Alternative Solution with ES6
With the advent of ES6, a new and concise solution is available: the Array.from() function. This function can quickly and easily create an array from any iterable object, including NodeLists.
// nl is a NodeList let myArray = Array.from(nl)
Conclusion
While the for loop approach may offer surprising speed in certain browsers, the Array.from() function provides a modern and cross-platform solution for converting NodeLists to arrays.
The above is the detailed content of Is `slice()` Still The Fastest Way to Convert a NodeList to an Array?. For more information, please follow other related articles on the PHP Chinese website!