in reply to quickness is not so obvious

Don’t “diddle” code to make it faster.   Find a better algorithm.

Kernighan & Plauger:   The Elements of Programming Style

Proof-positive that great wisdom sometimes comes in tiny books.

Replies are listed 'Best First'.
Re^2: quickness is not so obvious
by RonW (Parson) on Jan 22, 2015 at 18:29 UTC

    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.)

      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.

Re^2: quickness is not so obvious
by Your Mother (Archbishop) on Jan 22, 2015 at 23:22 UTC

    Echoing what RonW said, I think that particular reasoning is from a pre-high-level language mindset where there aren’t all that many ways to write a piece of code and they will often collapse to a similar number of ops when compiled. There are so many ways to write a line or block or package of Perl that diddling is harder to define… but you should know it when you see it. Apologies to the ghost of Justice Stewart.