![]() |
VOOZH | about |
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:
Below code counts the number of increment operations executed in FIRST and SECOND, and prints the counts.
Count in FIRST = 1010 Count in SECOND = 1100
Below code counts the number of comparison operations executed by FIRST and SECOND
Count for FIRST 1021 Count for SECOND 1201
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.