search
HomeWeb Front-endJS TutorialWhich type of loop is fastest in JavaScript? Comparison of several for loops

Which type of loop is fastest in JavaScript? Comparison of several for loops

JavaScript is the “evergreen tree” in the field of web development. Whether it is JavaScript frameworks (such as Node.js, React, Angular, Vue, etc.) or native JavaScript, they all have a very large fan base. Let’s talk about modern JavaScript. Loops have always been an important part of most programming languages, and modern JavaScript gives us many ways to iterate or loop over values.

But the question is, do we really know which loop or iteration is best for our needs. There are many variations of the for loop, such as for, for (reverse order), for…of, forEach, for…in, for…await. This article will discuss these.

Understand which for loop or iterator is suitable for our needs to prevent us from making some low-level mistakes that affect application performance.

Which loop is faster?

The answer is actually: for(reverse order)

The most surprising thing to me is that when I am on my local computer After testing it, I had to accept the fact that for (in reverse order) is the fastest of all for loops. Below I will give an example of performing a loop through an array containing more than a million elements.

Statement : console.time() The accuracy of the results depends heavily on the system configuration on which we are running the test. You can learn more about accuracy here.

const million = 1000000; 
const arr = Array(million);

// 注:这是稀疏数组,应该为其指定内容,否则不同方式的循环对其的处理方式会不同:
// const arr = [...Array(million)]

console.time('⏳');
for (let i = arr.length; i > 0; i--) {} // for(倒序)  :- 1.5ms
for (let i = 0; i < arr.length; i++) {} // for          :- 1.6ms
arr.forEach(v => v)                     // foreach      :- 2.1ms
for (const v of arr) {}                 // for...of     :- 11.7ms
console.timeEnd(&#39;⏳&#39;);

The reason for this result is very simple. In the code, the forward and reverse for loops take almost the same time, with a difference of only 0.1 milliseconds. The reason is that for (reverse order) only needs to calculate the starting variable let i = arr.length once, while in the forward for loop, it is The condition i<arr.length> is checked every time the variable is incremented. This subtle difference is not very important and you can ignore it. (Translator's note: We can ignore it when the data volume is small or the code is not time-sensitive. However, according to the translator's test, when the data volume expands, such as billions, hundreds of billions, etc., the gap will increase significantly. , we need to consider the impact of time on application performance.) </arr.length>

And forEach is a method of the Array prototype, which is different from the ordinary for Compared to loops, forEach and for…of take more time to iterate through the array. (Translator's Note: But it is worth noting that both for…of and forEach obtain data from the object, but the prototype does not, so there is no comparison.)

Types of loops, and where we should use them

1. For loop (forward and reverse order)

I think maybe everyone should be very familiar with this basic cycle. We can use the for loop wherever we need to run a piece of code an approved number of times. The most basic for loop runs the fastest, so we should use it every time, right? No, performance is not just the only criterion. Code readability is often more important. Let us choose the variant that suits our application.

2. forEach

This method needs to accept a callback function as an input parameter. Iterate over each element of the array and execute our callback function (passing the element itself and its index (optional) as arguments). forEach also allows an optional parameter this in the callback function.

const things = [&#39;have&#39;, &#39;fun&#39;, &#39;coding&#39;];
const callbackFun = (item, idex) => {
    console.log(`${item} - ${index}`);
}
things.foreach(callbackFun); 
/* 输出   have - 0
        fun - 1
        coding - 2 */

It should be noted that if we want to use forEach, we cannot use JavaScript's short-circuit operators (||, &&...), that is, we cannot skip in each loop or end the loop.

3. for…of

##for…of It is standardized in ES6 (ECMAScript 6). It creates a loop over an iterable object (such as array, map, set, string, etc.) and has a The outstanding advantage is excellent readability.

const arr = [3, 5, 7];
const str = &#39;hello&#39;;
for (let i of arr) {
   console.log(i); // 输出 3, 5, 7
}
for (let i of str) {
   console.log(i); // 输出 &#39;h&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;
}

It should be noted that please do not use

for…of in the generator, even if the for…of loop terminates early. After exiting the loop, the generator is closed and an attempt is made to iterate again without producing any further results.

4. for in

for…in 会在对象的所有可枚举属性上迭代指定的变量。对于每个不同的属性,for…in 语句除返回数字索引外,还将返回用户定义的属性的名称。 因此,在遍历数组时最好使用带有数字索引的传统 for 循环。 因为 for…in 语句还会迭代除数组元素之外的用户定义属性,就算我们修改了数组对象(例如添加自定义属性或方法),依然如此。

const details = {firstName: &#39;john&#39;, lastName: &#39;Doe&#39;};
let fullName = &#39;&#39;;
for (let i in details) {
    fullName += details[i] + &#39; &#39;; // fullName: john doe
}

<span style="font-size: 16px;">for…of</span><span style="font-size: 16px;">for…in</span>

for…offor…in 之间的主要区别是它们迭代的内容。for…in 循环遍历对象的属性,而 for…of 循环遍历可迭代对象的值。

let arr= [4, 5, 6];
for (let i in arr) {
   console.log(i); // &#39;0&#39;, &#39;1&#39;, &#39;2&#39;
}
for (let i of arr) {
   console.log(i); // &#39;4&#39;, &#39;5&#39;, &#39;6&#39;
}

Which type of loop is fastest in JavaScript? Comparison of several for loops

结论

  • for 最快,但可读性比较差
  • foreach 比较快,能够控制内容
  • for...of 比较慢,但香
  • for...in 比较慢,没那么方便

最后,给你一条明智的建议 —— 优先考虑可读性。尤其是当我们开发复杂的结构程序时,更需要这样做。当然,我们也应该专注于性能。尽量避免增添不必要的、多余的花哨代码,因为这有时可能对你的程序性能造成严重影响。祝你编码愉快。

译者注

在译者的实际测试中,发现:

  • 不同浏览器甚至不同版本,结果会有不一样(颠倒,例如 Firefox 对原生 for-loop 似乎不太友好,Safari 极度喜欢 while)
  • 不同平台操作系统处理器,结果会有不一样

英文原文地址:https://medium.com/javascript-in-plain-english/which-type-of-loop-is-fastest-in-javascript-ec834a0f21b9

原文作者:kushsavani

本文转载自:https://juejin.cn/post/6930973929452339213

译者:霜羽 Hoarfroster

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of Which type of loop is fastest in JavaScript? Comparison of several for loops. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金--霜羽Hoarfroster. If there is any infringement, please contact admin@php.cn delete
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools