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