"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > NodeList to Array: Is `Array.from()` Really the Fastest?

NodeList to Array: Is `Array.from()` Really the Fastest?

Published on 2024-11-08
Browse:368

 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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3