以前面试的时候老有人问 ++i 和 i++ 的问题, 每每心里都在暗暗想…,
1、这俩东西功能不一样。
2、 写代码的时候多放些注意力在别的地方比在这个地方纠结强。
我总认为, 可读性和扩展性好的代码 比 一堆 又烂又快的代码好。
3、不免俗的研究了一下。
对于C
-
#include "stdio.h"
-
-
int main(int argc, char *argv[]) {
-
int i = 0;
-
-
int a = 0;
-
int b = 0;
-
-
a = i++;
-
b= ++i;
-
-
i++;
-
++i;
-
-
}
汇编后
-
.file "test.c"
-
.section .rodata
-
.LC0:
-
.string "%d"
-
.text
-
.globl main
-
.type main, @function
-
main:
-
pushl %ebp
-
movl %esp, %ebp
-
andl $-16, %esp
-
subl $32, %esp
-
movl $0, 28(%esp)
-
movl $0, 24(%esp)
-
movl $0, 20(%esp)
-
movl 28(%esp), %eax
-
movl %eax, 24(%esp)
-
addl $1, 28(%esp)
-
addl $1, 28(%esp)
-
movl 28(%esp), %eax
-
movl %eax, 20(%esp)
-
addl $1, 28(%esp)
-
addl $1, 28(%esp)
-
movl $.LC0, %eax
-
movl 24(%esp), %edx
-
movl %edx, 4(%esp)
-
movl %eax, (%esp)
-
call printf
-
movl $.LC0, %eax
-
movl 20(%esp), %edx
-
movl %edx, 4(%esp)
-
movl %eax, (%esp)
-
call printf
-
leave
-
ret
-
.size main, .-main
-
.ident "GCC: (Ubuntu/Linaro 4.4.4-14ubuntu5) 4.4.5"
-
.section .note.GNU-stack,"",@progbits
可以看出没有赋值操作的 自增运算 不管是 ++i 还是i++ 都会被会变成一条相同的汇编(addl $1, 28(%esp))
如果有赋值操作的时候 汇编的条数是一样的 只是 几条语句的顺序不一样
所以C中这两种格式区别仅在于生成的值, 所以在仅使用它们的副作用时, 二者 完全一样,
http://c-faq-chn.sourceforge.net/ccfaq/node46.htm
但是 C++同学的表现是不一样的有兴趣的同学google一下,
悲剧 刚才写的一段代码丢了
简单说下php同学吧
有兴趣的通许参阅一下php源码 大概在这个文件里zend_compile.c
stackoverflow上有一些简单的说明:
http://stackoverflow.com/questions/1756015/whats-the-difference-between-i-and-i-in-php
原文有一段
:For further clarification, post-incrementation in PHP has been documented as storing a temporary variable which attributes to this 10% overhead vs. pre-incrementation.
是说 post-incrementation i++ 比pre-incrementation ++i 花费多10% 来存储一个临时变量。