0

Which is faster in Swift? Pre-increment ++i, or post-increment i++?

Is it the same as in C++?

Preincrement faster than postincrement in C++ - true? If yes, why is it?

Community
  • 1
  • 1
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
  • 1
    Some folks just love to optimize to prematurely, do they not? – matt May 17 '15 at 15:06
  • Even for C++ the answer is (if I understand it correctly): "it depends". – Are you thinking of plain scalar types like Int (where it most probably makes no difference at all) or of class types (where it probably depends on your implementation of the ++ operator)? – Martin R May 17 '15 at 15:17
  • One of the things worth noting is that `++i` is theoretically faster than `i++`, as the latter requires a copy/temporary (an imaginary `j` which is left behind storing `i's` previous value). Even a compiler which is dumb enough could allocate an extra register here even for an `int`, though it would have to be an exceptionally poor optimizer of the kind you would never find in production and perhaps even rare among toy compilers. Still, it's not a bad idea to go with the general rule of thumb that pre-increment is as fast or faster, especially in languages that allow overloading it... –  May 18 '15 at 03:49
  • ... and adopt that stylistically in a uniform way for standalone statements, given that it either helps or it doesn't, but almost certainly can't be worse. –  May 18 '15 at 03:50

0 Answers0