When adding more than 2 arrays, separate loops for adding elements step by step prove to give a better performance than adding the elements in a single loop.
To Test the above statement, two code blocks add the 4 array elements namely array a with b and c with d. The first code block uses a combined loop to add them while the second block uses two different for loops. Clock is used in both the programs for measuring the time taken to execute the loops.
Using Combined Loop
seconds = 2.47865
Using Separate Loop
seconds = 2.07937
Note : Actual Output time depends on the compiler used
As we can see from the above examples separate loops are faster in addition than in combined loops. Reason for this is that assuming a simple LIFO caching policy, separate loop would first cause a and b to be loaded into RAM and then be worked on entirely in RAM. When the second loop starts, c and d would then be loaded from disk into RAM and operated on. Thus the arrays are loaded once into the memory.
While the combined loop will page out two arrays and page in the other two every time around the loop. Thus combined loop would be much slower since page in page out has to occur repeatedly compared to separate loops where arrays are loaded once and worked upon.
- Python | Plotting Combined charts in excel sheet using XlsxWriter module
- Why is === faster than == in PHP ?
- Why is C considered faster than other languages ?
- getchar_unlocked() - faster input in C/C++ for Competitive Programming
- Program to implement Separate Chaining in C++ STL without the use of pointers
- Dividing a Large file into Separate Modules in C/C++, Java and Python
- ES6 | Loops
- Nested Loops in C with Examples
- Understanding for loops in Java
- PHP break (Single and Nested Loops)
- Sum of array Elements without using loops and recursion
- C | Loops & Control Structure | Question 5
- C | Loops & Control Structure | Question 4
- C | Loops & Control Structure | Question 2
- C | Loops & Control Structure | Question 1
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.