i++ less efficient than ++i, how to show this?

前端 未结 9 1868
暖寄归人
暖寄归人 2020-12-03 14:30

I am trying to show by example that the prefix increment is more efficient than the postfix increment.

In theory this makes sense: i++ needs to be able to return the

9条回答
  •  星月不相逢
    2020-12-03 15:07

    Several points:

    • First, you're unlikely to see a major performance difference in any way
    • Second, your benchmarking is useless if you have optimizations disabled. What we want to know is if this change gives us more or less efficient code, which means that we have to use it with the most efficient code the compiler is able to produce. We don't care whether it is faster in unoptimized builds, we need to know if it is faster in optimized ones.
    • For built-in datatypes like integers, the compiler is generally able to optimize the difference away. The problem mainly occurs for more complex types with overloaded increment iterators, where the compiler can't trivially see that the two operations would be equivalent in the context.
    • You should use the code that clearest expresses your intent. Do you want to "add one to the value", or "add one to the value, but keep working on the original value a bit longer"? Usually, the former is the case, and then a pre-increment better expresses your intent.

    If you want to show the difference, the simplest option is simply to impement both operators, and point out that one requires an extra copy, the other does not.

提交回复
热议问题