[Solved] Efficient checking for NULL pointers in function called millions of times [closed]


GNU C compiler has a __builtin_expect to tell the optimizer the most probable outcome of a value.

It is not standard C though.

You can #define macros to wrap around it and conditionally switch which definition to use, based on the compiler.

Linux kernel uses it this way (include/linux/compiler.h):

#define likely(x)      __builtin_expect(!!(x), 1)
#define unlikely(x)    __builtin_expect(!!(x), 0)

The ifs then become:

if (likely(an_expression)) { ... } 

if (unlikely(another_expression)) { ... }

2

solved Efficient checking for NULL pointers in function called millions of times [closed]