L*******e 发帖数: 114 | 1 I know for y=x++, definitely a temp variable holds the old value.
How about this: for(int i=0;i<100;i++) or even simpler i++?
From the claim from http://www.gotw.ca/gotw/002.htm, but I do not agree this claim, why a temp var is created but not used at all? see the following sample program and generated assembly.
Any thoughts?
int i = 0;
i++;
++i;
int k=i++;
assembly generated by g++:
movl $0, -12(%ebp) #, i
addl $1, -12(%ebp) #, i
addl $1, -12(%ebp) | z***9 发帖数: 696 | 2 depends on if you use -O2 or O3 with g++ | r**u 发帖数: 1567 | 3 i++,先要用额外的地方存原始值,返回这个值,然后+1。
++i,就直接在原来的地址+1,然后返回。
理论上++i,快一点。不过好像compiler已经都optimize了,
i++也不会要额外存原始值。
有人说如果i是iterator,difference会比较大。
【在 L*******e 的大作中提到】 : I know for y=x++, definitely a temp variable holds the old value. : How about this: for(int i=0;i<100;i++) or even simpler i++? : From the claim from http://www.gotw.ca/gotw/002.htm, but I do not agree this claim, why a temp var is created but not used at all? see the following sample program and generated assembly. : Any thoughts? : int i = 0; : i++; : ++i; : int k=i++; : assembly generated by g++: : movl $0, -12(%ebp) #, i
| h**k 发帖数: 3368 | 4 如果用在for循环语句里,i++和++i是一样的,被编译器直接优化了,都不生成临时变
量。
【在 r**u 的大作中提到】 : i++,先要用额外的地方存原始值,返回这个值,然后+1。 : ++i,就直接在原来的地址+1,然后返回。 : 理论上++i,快一点。不过好像compiler已经都optimize了, : i++也不会要额外存原始值。 : 有人说如果i是iterator,difference会比较大。
| L*******e 发帖数: 114 | 5 I was asked this question during on-site. My answer was pre-increment
because of temp var used in post-increment. However, rethink the question,
there is no definite yes or no answer.
Another similar question is "does inline make program faster?" I was asked
too (just different interviewer)
【在 h**k 的大作中提到】 : 如果用在for循环语句里,i++和++i是一样的,被编译器直接优化了,都不生成临时变 : 量。
| h**k 发帖数: 3368 | 6 在老编译器上,可以同时使用++i和i++的情况下,毫无疑问的使用++i更好,原因就是i
++需要生成临时变量。最新的编译器已经优化了,没有区别。
使用inline函数的缺点是执行代码变大了,这需要更大的内存,同时也增加了page
fault的可能,这往往会减慢程序的运行。
【在 L*******e 的大作中提到】 : I was asked this question during on-site. My answer was pre-increment : because of temp var used in post-increment. However, rethink the question, : there is no definite yes or no answer. : Another similar question is "does inline make program faster?" I was asked : too (just different interviewer)
|
|