in reply to &1 is no faster than %2 when checking for oddness. Oh well.
About all this entire thread has proven to me is that the difference is not significant, regardless of which one comes out on top. So I'll repeat myself here: choose the behaviour that says what you mean over the one that seems to be faster (today).
As tye pointed out, this type of optimisation can run you into loads of trouble if you forget about the range of your integers. However, if you stick to using % to determine "oddness", you're much more likely to stick within the range that perl supports. Getting it right for sum(1..n) when n gets up over 92_681, for example, may be important later. And because perl abstracts numbers that are too big to be held in an integer, the modulo continues to work.
Use & when you want to say "I'm twiddling bits". Use % when you want to say "I'm finding the remainder (if any)". Since the definition of odd (at least on the set of integers) is "not even" and the definition of even is "divisible by two with no remainder", it seems only logical to use % to find it.
Of course, it's also easily extensible to finding multiples (or not) of other numbers, too... Let the hardware guys worry about these optimisations. At some point, some guy at AMD or Intel or whomever will decide that evenness is important enough that when it seems a modulo operation where the divisor is 2 (or a power of 2), it switches to bit-twiddling. Even then, perl will still get it right for large numbers because it won't use the normal modulo operator when the numbers are too big, taking advantage of the hardware's ability to optimise normal numbers while not losing the accuracy of perl's abstractions.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: &1 is no faster than %2 when checking for oddness. Oh well.
by BrowserUk (Patriarch) on Nov 16, 2006 at 17:32 UTC | |
by Tanktalus (Canon) on Nov 16, 2006 at 17:49 UTC | |
by BrowserUk (Patriarch) on Nov 16, 2006 at 18:57 UTC | |
by Limbic~Region (Chancellor) on Nov 16, 2006 at 17:45 UTC | |
by BrowserUk (Patriarch) on Nov 16, 2006 at 19:00 UTC | |
by Limbic~Region (Chancellor) on Nov 16, 2006 at 20:13 UTC | |
by BrowserUk (Patriarch) on Nov 16, 2006 at 20:21 UTC |