在C if-else语句中,是否应该首先出现更可能的条件?

Zhi*_*ang 6 c compiler-construction performance

我碰巧写了一个if-else语句,条件在大多数时候都是假的(检查是否分配了静态指针).编译器优化哪一个会更好?或者他们是平等的?该函数将被调用很多次,因此优化其性能至关重要.

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
  }
}
Run Code Online (Sandbox Code Playgroud)

egu*_*gur 5

一些编译器可以允许开发人员指定哪个条件更有可能或不太可能发生.这在Linux内核中大量使用.

在gcc中,有可能的(x)或不太可能的(x)宏.例:

if (unlikely(p == NULL)) {
    p = malloc(10);
}
Run Code Online (Sandbox Code Playgroud)