# 09.slowpath和fastpath

在日常阅读OC源码的过程中经常会遇到这两个宏定义。它是什么意思呢？

```cpp
//x很可能为真， fastpath 可以简称为 真值判断
#define fastpath(x) (__builtin_expect(bool(x), 1)) 
//x很可能为假，slowpath 可以简称为 假值判断
#define slowpath(x) (__builtin_expect(bool(x), 0))
```

其中的 `__builtin_expect` 指令是由 `gcc` 引入的

* 目的：编译器可以对代码进行优化，以减少指令跳转带来的性能下降。即性能优化
* 作用：允许程序员将最有可能执行的分支告诉编译器。
* 指令的写法为：`__builtin_expect(EXP, N)` 。表示 EXP==N的概率很大。
* `fastpath` 定义中 `__builtin_expect((x),1)` 表示 x 的值为真的可能性更大；即 执行if 里面语句的机会更大
* `slowpath` 定义中的 `__builtin_expect((x),0)` 表示 x 的值为假的可能性更大。即执行 else 里面语句的机会更大
* 在日常的开发中，也可以通过设置来优化编译器，达到性能优化的目的，设置的路径为：`Build Setting` --> `Optimization Level` --> `Debug` --> `将None 改为 fastest 或者 smallest`


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ryukiedev.gitbook.io/wiki/ios/di-ceng/09.slowpath-and-fastpath.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
