I happened to write a if-else statement, the condition would be false at most time(check a static pointer is assigned or not). Which one would be better for the compiler to optimize? Or they are just equal?. The function would be called so many times, so it is critical to optimize its performance.
void foo() {
static int * p = NULL;
if (p == NULL) {
p = (int *) malloc( SIZE * sizeof(int));
}
//do something here
}
void foo() {
static int * p = NULL;
if (p != NULL) {
//do something here
} else {
p = (int *) malloc( SIZE * sizeof(int));
//do something
}
}
Two or more expressions can be evaluated together using logical operators to check if two expressions evaluate to true together, or at least one of them. To check if two expressions both evaluate to true , use the AND operator && . To check if at least one of the expressions evaluate to true , use the OR operator || .
C has the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true. Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false.
The If-Else statement The general form of if-else is as follows: if (test-expression) { True block of statements } Else { False block of statements } Statements; n this type of a construct, if the value of test-expression is true, then the true block of statements will be executed.
Conditional statements help you to make a decision based on certain conditions. These conditions are specified by a set of conditional statements having boolean expressions which are evaluated to a boolean value of true or false.
Some compilers can allow the dev to specify which is condition is more likely or unlikely to occur. This is heavily used in the Linux kernel.
In gcc, there's the likely(x) or unlikely(x) macros. Example:
if (unlikely(p == NULL)) {
p = malloc(10);
}
If the function is called often enough to not be evicted from the branch predictor, then the predictor will take care of everything for you, since it will learn very quickly which is the "likely" branch.
Some compilers allow you to decorate conditionals with prediction hints. Check your vendor's documentation, and add a hint if you can.
Specific platforms document the default predictor behaviour (e.g. see the Intel Optimization Manual for x86), but it's best left to your compiler to implement that via the aforementioned hints. In fact, you don't really have a choice, since you don't control your compilers code generation anyway, so the only last measure left to you would be to write the code in machine code yourself and implement the platform's advice on default prediction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With