The Optimal Conversion from JavaScript NodeList to Array: Performance Comparison
Previous discussions have suggested that converting a NodeList to an array using Array.prototype.slice.call(nl) is the most efficient approach. However, recent performance benchmarks have challenged this notion.
Benchmarking the Two Methods
While the Array.prototype.slice.call(nl) method is widely regarded as fast, experiments in Chromium 6 have shown that it is significantly slower than a simple for loop:
<code class="javascript">// Using a 'for' loop var arr = []; for(var i = 0, n; n = nl[i]; ++i) arr.push(n);</code>
This result may come as a surprise, given the perceived efficiency of the slice() method.
Enter ES6's Array.from()
With the advent of ES6, we now have a streamlined solution to this task: the Array.from() function. This function allows us to create an array from an iterable object, which includes NodeLists.
<code class="javascript">// Using Array.from() let myArray = Array.from(nl)</code>
Performance Benefits of Array.from()
Array.from() outperforms both slice() and the simple for loop in terms of speed. This is attributed to its optimized implementation, which leverages the ES6 spread operator to efficiently create the array.
Conclusion
While the old techniques for converting NodeLists to arrays may still have their uses, the introduction of Array.from() has established it as the fastest and most convenient approach. By leveraging ES6's advanced features, developers can now effortlessly and efficiently perform this conversion.
The above is the detailed content of Is Array.from() Truly the Fastest Way to Convert a NodeList to an Array?. For more information, please follow other related articles on the PHP Chinese website!