for loop optimization in C++

Bhushit Anjaria
2 min readAug 19, 2021

Each nanosecond saved matters when you are concerned about the speed. So small small optimization matters when you want to overall increase your performance. When you review your or your project’s source you can find the standard for loop shown below. Even As a developer including me used to write for loop as shown below

for (lnLoopCounter = 0; lnLoopCounter < lnMaxLoopIteratorCount; lnLoopCounter++)

But there is another way of writing a for loop which seems hard to read for beginners but it gives better performance. The second option with better performance is shown below

for (lnLoopCounter = lnMaxLoopIteratorCount; lnLoopCounter--; )

I have tested the code with different loop iteration and found that second option is faster

Result for time taken by different loop in nanoseconds for loop iterations are shown in the below image:

Notes :

  1. results may vary in different systems.
  2. chrono library is used to calculate the time difference.

The sample code written by me is given below for the reference.

#include <iostream
#include <chrono>
int main()
{
char ch = 'n';
do
{
long int lnLoopCounter = 0, lnLoop1Variable = 0, lnLoop2Variable = 0;
long int lnMaxLoopIteratorCount = 10;
std::cout << "Enter loop iteration count : ";
std::cin >> lnMaxLoopIteratorCount;
// loop 1 start time
auto Loop1StartTime = std::chrono::high_resolution_clock::now();
// loop 1 : standard looping used by the developers
for (lnLoopCounter = 0; lnLoopCounter < lnMaxLoopIteratorCount; lnLoopCounter++)
{
++lnLoop1Variable; // incrementing loop 1 variable
}
// loop 1 elapsed time
auto Loop1ElapsedTime = std::chrono::high_resolution_clock::now() - Loop1StartTime;
// calculating loop 1 execution time
long long Loop1ExecutionTime = std::chrono::duration_cast<std::chrono::nanoseconds>(Loop1ElapsedTime).count();
// loop 2 start time
auto Loop2StartTime = std::chrono::high_resolution_clock::now();
// loop 2 : optimized loop which may be difficult to read but faster execution
for (lnLoopCounter = lnMaxLoopIteratorCount; lnLoopCounter--; )
{
++lnLoop2Variable; // incrementing loop 2 variable
}
// loop 2 elapsed time
auto Loop2ElapsedTime = std::chrono::high_resolution_clock::now() - Loop2StartTime;
long long Loop2ExecutionTime = std::chrono::duration_cast<std::chrono::nanoseconds>(Loop2ElapsedTime).count(); // calculating loop 2 execution time
std::cout << "Value of lnLoop1Variable is " << lnLoop1Variable << " time taken in nanoseconds for loop 1 execution is " << Loop1ExecutionTime << std::endl;
std::cout << "Value of lnLoop2Variable is " << lnLoop2Variable << " time taken in nanoseconds for loop 2 execution is " << Loop2ExecutionTime << std::endl;
std::cout << std::endl << "Press 'y' and enter to repeat the test. ";

std::cin >> ch;
std::cout << std::endl;
} while (ch == 'y');
return EXIT_SUCCESS;
}

--

--