


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('⏳');
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.)
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 = ['have', 'fun', 'coding']; 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 = 'hello'; for (let i of arr) { console.log(i); // 输出 3, 5, 7 } for (let i of str) { console.log(i); // 输出 'h', 'e', 'l', 'l', 'o' }
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: 'john', lastName: 'Doe'}; let fullName = ''; for (let i in details) { fullName += details[i] + ' '; // fullName: john doe }
<span style="font-size: 16px;">for…of</span>
和 <span style="font-size: 16px;">for…in</span>
for…of
和 for…in
之间的主要区别是它们迭代的内容。for…in
循环遍历对象的属性,而 for…of
循环遍历可迭代对象的值。
let arr= [4, 5, 6]; for (let i in arr) { console.log(i); // '0', '1', '2' } for (let i of arr) { console.log(i); // '4', '5', '6' }
结论
-
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service
