9

To preincrement or to postincrement?

for(var i = 0; i<length; ++i){
}

or

for(var i = 0; i<length; i++){
}

I would imagine on a good vm or compiler this would be optimized anyway. So does it really matter?

Comments
  • 9
    Even with -O0 they're identical on GCC and Clang so it doesn't really matter

    https://godbolt.org/z/xL-hcx
    https://godbolt.org/z/H7Cb-v

    I guess preincrement is the more sensible of the two so why not go with that one
  • 3
    .foreach
  • 3
    @yellow-dog Now *that* will be slower (except for Rust and possibly C++)
  • 0
    @12bitfloat tell me why would streaming be slower than iterating
  • 6
    @yellow-dog Because you're allocating an iterator/stream object -- likely on the heap for managed memory languages -- then you have dynamic dispatch overhead of calling the next method or if passing a lambda you again have the overhead of an object allocation and dynamic dispatch

    In most languages a simple for loop will be faster. But of course it all depends on the implementation and I couldn't quite figure out what language @Demolishun was talking about since he's a C++ guy but the example looks like Java or JavaScript
  • 5
    ++i or i++ doesn't matter if i is a plain old data type, which is always the case in C. In C++ however, it might be some object type with overloaded addition operator, and then ++i may be faster.
  • 1
    @12bitfloat it would turn out, you tried to be smarter than the compiler

    @highlight

    edit: i love how my terminal doesnt copy formatting
  • 0
  • 4
    @Fast-Nop s answer is the right one. This used to matter in ancient c compilers from the 70s and 80s just because they did the dumbest thing possible and it would add a pointless memory op if you did post increment, but that hasn’t been the case for more than 30 years. Even the most rudimentary IRs can figure out there are no side effects of that copy.

    Extra emphasis on this being slower if you use complex types though, I.e. an iterator. Overloaded operators if they can’t be inlined cause unbounded side effects and so do copy constructors. Therefore they have to be run if not inlined.
  • 1
    @highlight dude you calculated time1 twice
  • 1
  • 1
    *cough sorry cough* @yellow-dog
  • 0
    @melezorus34 intentionally 😳
  • 0
    @yellow-dog Wait what am I looking at though
  • 5
    It matters if it's 1985
  • 2
    Even if it isn't 1985, it's good practice to use the preincrement.

    Remember, code is there not only for the compiler, but also for programmers. Preincrement describes your intent more closely than postincrement does.
Add Comment