Why does a nested loop perform much faster than the flattened one?
Python provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking time.
In this article, we will see why does a nested loop performs better than the flattened one. But first, let’s see what is a nested loop and what is a flattened loop.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
- Nested loops are the logical structure in computer programming and coding. In which one loop statement is inside another loop statement.
for [iter_1] in [sequence_1]: for [iter_2] in [sequence_2]: # statements of inner loop statements(iter_2) # statements of outer loop statements(iter_1)
- Loops have the ability to iterate over the items of any sequence, such as a list or a string.
for [iter] in sequence: statements(s)
When we run our python script, the operating system we are running on will assign a Process ID for it. It can be interrupted by system calls and its priority can be changed over time. But the system is not likely to take resources away from a process when we change memory address or values. When we run flat for loop it is assigning much fewer variables than a nested loop. So we can say that a nested loop utilizes resources more than a flat loop if they are available.
For flattened loop: 2.7894973754882812e-05 For nested loop: 4.9114227294921875e-05 For flattened loop: 0.0002155303955078125 For nested loop: 0.00024271011352539062 For flattened loop: 0.0007171630859375 For nested loop: 0.0007529258728027344 For flattened loop: 0.0016894340515136719 For nested loop: 0.0012614727020263672 For flattened loop: 0.0029077529907226562 For nested loop: 0.0022766590118408203 For flattened loop: 0.004510402679443359 For nested loop: 0.003597736358642578 For flattened loop: 0.007539272308349609 For nested loop: 0.0057599544525146484 For flattened loop: 0.01167440414428711 For nested loop: 0.008468151092529297 For flattened loop: 0.016645431518554688 For nested loop: 0.01381683349609375
We can see that the time taken by the nested loop decreases for the increasing value of n.