in reply to Re^3: &1 is no faster than %2 when checking for oddness. (Careful what you benchmark)
in thread &1 is no faster than %2 when checking for oddness. Oh well.

The reason the code assigns to a variable outside the scope of block is to avoid a smart optimizer optimizing the '&' or '% 2' away, as the result isn't used at all. I didn't want to dive into the Perl source code and see whether '&' or '%' checked their context and decide to do nothing in void context. If one or both would do so, the benchmark would be flawed. It's the same for an assignment to a variable that's about to go out of scope; if the variable doesn't have magic attached, one might not do the assignment after all. I've been bitten by the optimizations Perl makes so many times when benchmarking, I'm very careful and try to give the leave as little room for short cuts as possible. Hence my preference for assigning to a variable whose scope goes beyond the block being tested.

As for your version, Perl parses ++$counter1 & 1 and 1 as '???' if ++$counter1 & 1. I don't know how much that means for the benchmark.

Replies are listed 'Best First'.
Re^5: &1 is no faster than %2 when checking for oddness. (Careful what you benchmark)
by BrowserUk (Patriarch) on Nov 16, 2006 at 15:11 UTC

    FYI: From the Deparse POD:

    Expand conventional syntax constructions into equivalent ones that expose their internal operation. LEVEL should be a digit, with higher values meaning more expansion. As with -q, this actually involves turning off special cases in B::Deparse's normal operations.
    c:\test>perl -MO=Deparse,-x9 -e"++$counter &1 and 1" ++$counter & 1 and '???'; -e syntax OK

    And to convince you that actually does what is required:

    c:\test>perl -e"++$counter &1 and 1; print $counter" 1

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.