in reply to Re: quickness is not so obvious
in thread quickness is not so obvious

Sometimes, implementation details do make a difference. Even with today's advanced optimizing compilers. And in the embedded systems world, where US$ 0.50 processors rule, the best available compilers often do not have the most advanced optimizers.

Example (in C):

i = count; j = 0; do { // something with j j++; } while (--i);

is often faster than the common: for (j = 0; j < count; j++) { } or even: for (i = count, j = 0; i; --i, j++) { }

This is because it's easy for an optimizer to "see" it can safely "replace" while (--i) with a decrement-and-branch-if-not-zero instruction.

(Also, if your code functions equally correctly with a decrementing "index", you can skip the extra variable and associated increment.)

Replies are listed 'Best First'.
Re^3: quickness is not so obvious
by GrandFather (Saint) on Jan 23, 2015 at 11:09 UTC

    If you are worried about dumb compilers why do you use post increment operators where the code logic doesn't care if it's a pre or post operator? Post "requires" an intermediate variable to save the pre-incremented value so it can be returned post increment.

    This preference for post increment is pervasive and I can't think why that should be. To me pre-increment is king because it puts the operator out front where I can see it instead of hiding the operator behind a variable. I expect most modern compilers would optimise the code if the "return" value's not used in any case, but in an embedded context where the odd nano-second may be important using post-increment by default seems really odd if you don't trust the compiler.

    Perl is the programming world's equivalent of English

      Coding guidelines. (Which have turned in to habit.)

      Though it has been several years since I last saw a compiler allocate a temporary - or even an extra register - to a post-increment or -decrement in a void context.

      And even in a non-void context, on many micros, the compiler will use an in-place inc/dec instruction so no extra register or temporary required.

        But why is it though a good thing to hide the operator after the variable? Saying "Coding guidelines" doesn't say anything about why it's a good idea. It's the reason behind the rule that I'm interested in.

        Perl is the programming world's equivalent of English