use*_*er7 10 c performance increment
在x = x + 1
,x
评估两次?如果是这样,这意味着什么x += 1
,x
只评估一次?两个表达式如何根据编译器中间代码进行评估?
例如,x++
可能意味着:获取位置x
,将内容加载x
到寄存器中,并增加x
内存中的值.
另外我读过,x += 1
当x
它不是一个简单的变量,而是一个涉及数组的表达式时很有用.任何想法为什么会这样?
sid*_*yll 15
只是为了给你一个"真实世界"的例子,考虑这个程序:
int main()
{
int i = 0;
i += 1;
i++;
i = i + 1;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用以下标志在达尔文11中使用GCC进行编译:
-S
停在汇编程序中-m32
到32位平台,只是为了简化一些事情将生成以下程序,除了我添加的注释和空行.请特别注意评论.
.section __TEXT,__text,regular,pure_instructions
.globl _main
.align 4, 0x90
_main:
pushl %ebp # cdecl function stuff
movl %esp, %ebp #
subl $12, %esp # get room for variables
movl $0, -12(%ebp) # i = 0;
; i += 1
movl -12(%ebp), %eax # load i in register a
addl $1, %eax # add 1 to register a
movl %eax, -12(%ebp) # store it back in memory
; i++
movl -12(%ebp), %eax #
addl $1, %eax # just the same
movl %eax, -12(%ebp) #
; i = i + 1
movl -12(%ebp), %eax #
addl $1, %eax # just the same
movl %eax, -12(%ebp) #
movl $0, -8(%ebp)
movl -8(%ebp), %eax
movl %eax, -4(%ebp)
movl -4(%ebp), %eax
addl $12, %esp
popl %ebp
ret
.subsections_via_symbols
Run Code Online (Sandbox Code Playgroud)
为什么x + = 1比x = x + 1更有效?
事实并非如此.
为什么x ++比x + = 1更有效?
事实并非如此.
之所以宁愿x += 1
要x = x+1
来的时候大约x
被替换为更长的标识,或在类或结构也许是场.在这种情况下,x += 1
版本更具可读性,更重要的是避免重复自己的陷阱.