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.