Which of the following two code segments is faster? Assume that compiler makes no optimizations.
Both code segments provide same functionality, and the code inside the two for loops would be executed same number of times in both code segments.
If we take a closer look then we can see that the SECOND does more operations than the FIRST. It executes all three parts (assignment, comparison and increment) of the for loop more times than the corresponding parts of FIRST:
- The SECOND executes assignment operations ( j = 0 or i = 0) 101 times while FIRST executes only 11 times.
- The SECOND does 101 + 1100 comparisons (i < 100 or j < 10) while the FIRST does 11 + 1010 comparisons (i < 10 or j < 100).
- The SECOND executes 1100 increment operations (i++ or j++) while the FIRST executes 1010 increment operation.
Below C++ code counts the number of increment operations executed in FIRST and SECOND, and prints the counts.
Below C++ code counts the number of comparison operations executed by FIRST and SECOND
Thanks to Dheeraj for suggesting the solution.
Please write comments if you find any of the answers/codes incorrect, or you want to share more information about the topics discussed above.
- Difference between while(1) and while(0) in C language
- goto statement in C/C++
- Continue Statement in C/C++
- Switch Statement in C/C++
- C Program to print numbers from 1 to N without using semicolon?
- Functions in C/C++
- Arrays in C/C++
- Interesting facts about switch statement in C
- Importance of function prototype in C
- Functions that are executed before and after main() in C
- Data type of case labels of switch statement in C++?
- Write one line functions for strcat() and strcmp()
- How are variables scoped in C - Static or Dynamic?
- Why C treats array parameters as pointers?
- For Versus While