Thursday, September 26, 2019

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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...