Use Postfix Operators Only When Necessary

C++ Primer 4/e 在算式這裡還有一個忠告:『Readers from a C background might be surprised that we use the prefix increment in the programs we’ve written. The reason is simple: The prefix version does less work. It increments the value and returns the incremented version. The postfix operator must store the original value so that it can return the unincremented value as its result. For ints and pointers, the compiler can optimize away this extra work. For more complex iterator types, this extra work potentially could be more costly. By habitually favoring the use of the prefix versions, we do not have to worry if the performance difference matters.』

中文版的是這樣說:『擁有C背景的讀者,可能會對我們在先前程式中使用前置式(prefix)increment運算子感到驚訝。理由很簡單:前置式版本做的動作比較少。它遞增其值並返回已變值。後置式版本則必須先儲存原值,才能返回該原值作為結果。對於ints和pointers,編譯器最佳化可將這額外的動作去除。但對於較複雜的iterator型別,這個額外動作的潛在代價可能很高。如果養成使用前置式版本的習慣,我們就不需擔心效率差異。』

我習慣使用後置是的版本,但還真沒想到前置是的版本效率上也有差異。

achi’s English Blog

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *