pull down to refresh
100 sats \ 1 reply \ @nullcount 12 Feb \ on: Programmer’s paranoia or obsession with performance? bitdevs
Adding a loop and switch statement might be more readable/maintainable if you ever need to add more bits to check in the future.
However, if your only concern is raw performance, you're better off with just if-else statements.
Modern compilers do all sorts of witchcraft to automatically optimize your code. If-else chains can be optimized into efficient branch predictions. Some compilers will automatically flatten predictable if-else chains to minimize incorrect predictions.
You could further optimize your if-else example by avoiding deeply-nested if statements. This helps readability, and it helps the compiler make better branch predictions.
for example:
You can also specify hints for the complier that inform it's branch prediction optimizations: https://www.geeksforgeeks.org/branch-prediction-macros-in-gcc/
Sometimes, doing extra work (like pre-sorting an array) can lead to faster execution because the complier can make better predictions in some scenarios if it knows the array is sorted.
The only way to know for sure? Try many approaches and actually test how they perform at scale.
I agree that the if-else performs better than the switch inside the for loop.
The recommendation you suggested:
if (TypeMsgToSend_ui16 & MESSAGE_TEST_MESSAGE) {
TypeMsgToSend_ui16 &= ~(MESSAGE_TEST_MESSAGE);
Encode_Command(RUT_COMMAND_TO_EXECUTE_SMS_SEND, PHONENUMBER, TEST_MESSAGE_TEXT);
}
if (TypeMsgToSend_ui16 & MESSAGE_RESET_CONFIRMATION) {
TypeMsgToSend_ui16 &= ~(MESSAGE_RESET_CONFIRMATION);
Encode_Command(RUT_COMMAND_TO_EXECUTE_SMS_SEND, PHONENUMBER, RESET_CONFIRMATION_TEXT);
}
// Continue for other bits...
can't be used because the Encode_Command function could be executed multiple times depending on TypeMsgToSend_ui16. This shouldn't happen, as Encode_Command should only be called once each time this section of code is executed, which is why the if-else approach is needed.
reply