Member-only story

JavaScript Interview Questions

Does for-loop Nesting Order Affect Performance?

Shuai Li
3 min readSep 20, 2021

Question

Will there be a significant difference in the time it takes to execute the following two pieces of code?

Code1:

Code2:

Analysis

At first glance, both pieces of code are three-level nested for loops, each iterating 100 * 1000 * 1000 times.

So there should be no difference in performance?

Wait, wait, wait, be careful. The nesting order of the for loops of these two code pieces is actually different. In the first code, the outermost for loop executes 100 times and the innermost for loop executes 10,000 times. In the second code , on the other hand, executes the outermost for loop 10,000 times and the innermost for loop 100 times.

Does such a subtle difference affect the performance of the program?

--

--

Shuai Li
Shuai Li

Written by Shuai Li

An enthusiastic game player of Earth Online.

No responses yet