Home > Article > Web Front-end > NodeList to Array: Is `Array.from()` Really the Fastest?
Converting from NodeList to Array: Unveiling the Swiftest Approach
Previous discussions have suggested that utilizing Array.prototype.slice.call(nl) method offers the most efficient conversion from NodeList to Array. However, recent benchmarkings have revealed an astonishingly different reality. Contrary to popular belief, the traditional for-loop approach, for(var i = 0, n; n = nl[i]; i) arr.push(n);, surpasses the aforementioned method by a remarkable threefold margin.
This perplexing finding sparks curiosity: Is this a mere quirk of Chromium 6, or does an even swifter approach lie hidden? Fortunately, with the advent of ES6, we are presented with a solution that effortlessly outperforms both previously proposed methods.
Array.from(): The Ultimate Solution
The Array.from() function, introduced in ES6, provides a succinct and blazingly fast means of converting a NodeList to an Array. Its syntax is straightforward:
// nl is a NodeList let myArray = Array.from(nl)
This single line of code accomplishes the conversion with unmatched efficiency, eclipsing its predecessors by a significant margin. Thus, the quest for the swiftest conversion method culminates in the triumphant reign of Array.from(), offering developers an unparalleled solution for this essential task.
The above is the detailed content of NodeList to Array: Is `Array.from()` Really the Fastest?. For more information, please follow other related articles on the PHP Chinese website!