mirror of
https://github.com/LCTT/TranslateProject.git
synced 2024-12-23 21:20:42 +08:00
Translating Why const Doesn't Make C Code Faster.
This commit is contained in:
parent
49b4b1408a
commit
d123a06338
@ -39,14 +39,14 @@ void constByArg(const int *x)
|
||||
}
|
||||
```
|
||||
|
||||
调用 `printf()` 时,CPU 会通过指针从 RAM 中取得 `*x` 的值。很显然,`constByArg()` 会稍微快一点,因为编译器知道 `*x` 是常量,因此不需要在调用 `constFunc()` 之后再次获取它的值。 It’s just printing the same thing. Right? Let’s see the assembly code generated by GCC with optimisations cranked up:
|
||||
调用 `printf()` 时,CPU 会通过指针从 RAM 中取得 `*x` 的值。很显然,`constByArg()` 会稍微快一点,因为编译器知道 `*x` 是常量,因此不需要在调用 `constFunc()` 之后再次获取它的值。它仅是打印相同的东西。对吧?让我们来看下 GCC 在如下编译选项下生成的汇编代码:
|
||||
|
||||
```
|
||||
$ gcc -S -Wall -O3 test.c
|
||||
$ view test.s
|
||||
```
|
||||
|
||||
Here’s the full assembly output for `byArg()`:
|
||||
以下是函数 `byArg()` 的完整汇编代码:
|
||||
|
||||
```
|
||||
byArg:
|
||||
@ -73,7 +73,7 @@ byArg:
|
||||
.cfi_endproc
|
||||
```
|
||||
|
||||
The only difference between the generated assembly code for `byArg()` and `constByArg()` is that `constByArg()` has a `call constFunc@PLT`, just like the source code asked. The `const` itself has literally made zero difference.
|
||||
函数 `byArg()` 和函数 `constByArg()` 生成的汇编代码中唯一的不同之处是 `constByArg()` 有一句汇编代码 `call constFunc@PLT`,这正是源码中的调用。关键字 `const` 本身并没有造成任何汇编代码上的不同。
|
||||
|
||||
Okay, that’s GCC. Maybe we just need a sufficiently smart compiler. Is Clang any better?
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user