-
Direct initialization using a constructor vs copy initialization
These are exactly identical for
ints and will generate identical code. Use whichever one you prefer to read or what your code policies are, etc. -
!=could be faster in hardware than<The generated code won’t actually be
i < nvsi != n, it’ll be likei - n < 0vsi - n == 0. That is, you’ll get ajlein the first case and ajein the second case. All thejccinstructions have identical performance (see instruction set reference and optionization reference, which just list all thejccinstructions together as having throughput 0.5).Which is better? For
ints, probably doesn’t matter performance-wise.Strictly safer to do
<in case you want to skip elements in the middle, since then you don’t have to worry about ending up with an infinite/undefined loop. But just write the condition that makes the most sense to write with the loop that you’re writing. Also take a look at dasblinkenlight’s answer. -
++idoesn’t require the compiler to keep the old value ofiaround, which is whati++would do.Yeah that’s nonsense. If your compiler can’t tell that you don’t need the old value and just rewrite the
i++to++i, then get a new compiler. Those definitely will compile to the same code with identical performance.That said, it’s a good guideline to just use the right thing. You want to increment
i, so that’s++i. Only use post-increment when you need to use post-increment. Full stop.
That said, the real “new hotness” would definitely be:
for (int i : range(n)) { ... }