Wednesday, 3 August 2016

c - Local variables defined inside loop



I have a function and several nested loops in it. Each loop uses different variable that is not used by the others.



My question is motivated by optimization considerations.



Here it is: Which approach is better?




To define local variables inside the body of the loop



void aspProtocolDetectEvents()
{
uint8_t arrayIndex;
for( arrayIndex = 0; arrayIndex < sizeof(__aspProtocol_events); arrayIndex++ )
{
uint8_t contextBitPosition;
for(contextBitPosition = 0; __aspProtocol_events[arrayIndex] != 0; contextBitPosition++)

{
__aspProtocol_Event contextEvent = utils_getAbsoluteBitPosition(__aspProtocol_events, arrayIndex, contextBitPosition);
if( __aspProtocol_isRisenEvent(contextEvent) )
{
__aspProtocol_dispatchEvent(contextEvent);
__aspProtocol_clearEvent(contextEvent);
}
}
}
}



Or is it better to define all of them at the beginning of the function body like this?:



void aspProtocolDetectEvents()
{
uint8_t arrayIndex;
uint8_t contextBitPosition;
__aspProtocol_Event contextEvent;
for( arrayIndex = 0; arrayIndex < sizeof(__aspProtocol_events); arrayIndex++ )

{
for(contextBitPosition = 0; __aspProtocol_events[arrayIndex] != 0; contextBitPosition++)
{
contextEvent = utils_getAbsoluteBitPosition(__aspProtocol_events, arrayIndex, contextBitPosition);
if( __aspProtocol_isRisenEvent(contextEvent) )
{
__aspProtocol_dispatchEvent(contextEvent);
__aspProtocol_clearEvent(contextEvent);
}
}

}
}


I mean, I don't know if the compiler optimizes it. In aspect of code structure I would prefer the first example, but if it takes more time (for allocation each time the loop iterates) I will have to compromise, and use the second one.


Answer



As they're locals they'll be allocated on the stack. The compiler will do this by adjusting the stack pointer when the function is called to make sure it has enough space for all the locals.



I wouldn't worry about how the space is allocated for variables in nested scopes. If you think you are seeing speed issues when using scoped locals then use a profiler to measure, but I suspect worrying about this is a classic case of premature optimization. Instead write readable and maintainable code.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...