Incrementing: x++ vs x += 1

后端 未结 5 1924
囚心锁ツ
囚心锁ツ 2020-11-30 14:56

I\'ve read that many developers use x += 1 instead of x++ for clarity. I understand that x++ can be ambiguous for new developers and that x += 1 is always more clear, but i

5条回答
  •  孤街浪徒
    2020-11-30 15:39

    Consider you're a lazy compiler implementer and wouldn't bother writing OPTIMIZATION routines in the machine-code-gen module.

    x = x + 1;

    would get translated to THIS code:

    mov $[x],$ACC
    iadd $1,$ACC
    mov $ACC,$[x]
    

    And x++ would get translated to:

    incr $[x] ;increment by 1
    

    if ONE instruction is executed in 1 machine cycle, then x = x + 1 would take 3 machine cycles where as x++ would take 1 machine cycle. (Hypothetical machine used here).

    BUT luckily, most compiler implementers are NOT lazy and will write optimizations in the machine-code-gen module. So x = x+1 and x++ SHOULD take equal time to execute. :-P

提交回复
热议问题