|Syntactic Confectionery Delight|
Testing a number for oddnessby Falkkin (Chaplain)
|on Jan 23, 2001 at 03:29 UTC||Need Help??|
Falkkin has asked for the
wisdom of the Perl Monks concerning the following question:
Earlier today, in the CB, I talked with arturo about how to find out whether a given integer is even or odd.
The obvious way to do this involves something like: $odd = $num % 2;.
On the other hand, my CS professor claims that's a slow way of finding out the oddness of a number, and suggests something along the lines of: $odd = $num & 1; instead. This makes sense, because one would assume that a logical AND takes up less CPU time than a DIV instruction.
I decided to test this hypothesis using perl's Benchmark module, and was surprised at the results:
Here's the code:
And here, the results:
It appears that the "slow" method of computing this is actually faster, but I have no idea why. I was wondering if any monks here who know the internals of perl could provide any insight on this.
The only causes I can think of are: