为什么说"一般情况下++nc比nc=nc+1更高效"?
这让我回想起美国CSE学校计算机系乐团的那首"Coding in C"里有一句歌词"save some time with plus plus i"
为什么说"++i可以save some time"?
带着这个疑问,回想起以前学GNU/Linux下的汇编,看过将C程序反汇编分析程序效率的例子。决定自己也动手做个实验。
打开GNU小本,用emacs编写main.c和Makefile两个文件如下:
~/temp $ ls Makefile main.c ~/temp $ make gcc main.c gcc -S main.c ~/temp $ ls Makefile a.out main.c main.s ~/temp $ cat main.c int main(void) { int i=0; asm("#begin"); /* 用于反汇编成汇编程序后的识别标记 */ ++i; asm("#middle"); i=i+1; asm("#end"); return 0; } ~/temp $ cat Makefile all: gcc main.c gcc -S main.c clean: rm -f *~ a.out main.s ~/temp $ cat main.s .file "main.c" .text .globl main .type main, @function main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) pushl %ebp movl %esp, %ebp pushl %ecx subl $16, %esp movl $0, -8(%ebp) #APP # 5 "main.c" 1 #begin # 0 "" 2 #NO_APP addl $1, -8(%ebp) #APP # 7 "main.c" 1 #middle # 0 "" 2 #NO_APP addl $1, -8(%ebp) #APP # 9 "main.c" 1 #end # 0 "" 2 #NO_APP movl $0, %eax addl $16, %esp popl %ecx popl %ebp leal -4(%ecx), %esp ret .size main, .-main .ident "GCC: (Debian 4.3.2-1.1) 4.3.2" .section .note.GNU-stack,"",@progbits ~/temp $ |
由上可知,单独地用++i和i=i+1的效率是一样的,都对应于同一汇编语句
addl $1, -8(%ebp)
我表错情了......
++i一般比i=i+1高效应该是指
1. ++i比i=i+1少打几个字
2. 组合使用时,如
if (++num >= SAVED_LOG_LINES)
++end;
用++i的形式,表达紧凑(高效)很多
就当多一次小丑吧:)

参考资源
1. coding in c + 计算机系系列歌曲
http://bbs.linuxeden.com/thread-192532-1-1.html2. Professional_Assembly_Language.pdf GNU/Linux汇编
http://download.csdn.net/source/1250684
时间:2009-12-13 13:04
来源:Linuxeden
作者:c-aries
原文链接