cperformance

In the C if-else statement, should the condition which is more likely to be true come first?


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
  }
}

Solution

  • 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);
    }