在C if-else语句中,更可能成立的条件应该首先出现吗? [英] In the C if-else statement, should the condition which is more likely to be true come first?

查看:133
本文介绍了在C if-else语句中,更可能成立的条件应该首先出现吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

某些编译器可以允许开发人员指定哪种情况更有可能或不太可能发生。
这在Linux内核中大量使用。

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.

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

In gcc, there's the likely(x) or unlikely(x) macros. Example:

if (unlikely(p == NULL)) {
    p = malloc(10);
}

这篇关于在C if-else语句中,更可能成立的条件应该首先出现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆