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.
- Which will be faster while(1) or while(2)?
- Why is === faster than == in PHP ?
- Python | Plotting Combined charts in excel sheet using XlsxWriter module
- Why is C considered faster than other languages ?
- getchar_unlocked() - faster input in C/C++ for Competitive Programming
- How to keep compiled files in a separate directory ?
- 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
- Loops in R (for, while, repeat)
- 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 21
- C | Loops & Control Structure | Question 15
- C | Loops & Control Structure | Question 5
- C | Loops & Control Structure | Question 14
- C | Loops & Control Structure | Question 20
- C | Loops & Control Structure | Question 18