Is a += b more efficient than a = a + b in C?

前端 未结 7 1744
耶瑟儿~
耶瑟儿~ 2020-12-10 04:42

I know in some languages the following:

a += b

is more efficient than:

a = a + b

because it removes the n

7条回答
  •  臣服心动
    2020-12-10 05:03

    a += b
    

    is more efficient than

    a = a + b
    

    because the former takes you 6 keystrokes and the latter takes you 9 keystrokes.

    With modern hardware, even if the compiler is stupid and uses slower code for one than the other, the total time saved over the lifetime of the program may possibly be less than the time it takes you to type the three extra key strokes.

    However, as others have said, the compiler almost certainly produces exactly the same code so the former is more efficient.

    Even if you factor in readability, most C programmers probably mentally parse the former more quickly than the latter because it is such a common pattern.

提交回复
热议问题