Monday, 30 May 2016

Whether any performanace impacts will occur when we declare variable inside and outside of for loop in c or c++ programming?

 
Whether any performanace impacts will occur when we declare variable inside and outside of for loop in c  or c++ programming?

I think your answer will be yes.
But my answer is no(Terms and conditions apply) for POD types.
There will not be any performance impacts when declare the variable inside and outside the loop. But this depends upon your type is POD or non-POD Type.

Why there is no performance impacts for POD Types:

Compiler will do some magic in the name optimization for POD-types alone.
When you declare a variable inside the loop, compiler will optimize in such a way that it will not allocate memory for that variable for each iteration rather it will keep the variable as register. So no memory allocation is required at each time of iteration.

Why terms and conditions apply?

Remember this purely depends on your compiler. Standard is not giving guarantee for this.
If case your compiler is showing the performance impacts, then better you should throw your compiler.
Consider this for loop example:
for (int i=0;i<10;i++)
{
int a=10; // There is no performance impact because compiler will optimize it
MyClass obj; // There is performance impact
}

What about non-POD types like class or struct?


Yes there will be performance impact for the non-POD types this is because constructor need to be called at every iteration.