From: Paul Lutus Date: 2006-10-26T15:25:04+09:00 Subject: Re: simple math question Phrogz wrote: > Rick DeNatale wrote: >> (int & 1).zero? is probably faster than >> int[0].zero? >> >> Since the latter generates the mask using the bit position. >> >> and both should be faster than >> >> (int % 2).zero? >> >> But it it's performance critical, benchmarking is recommended to >> verify. One should never simply take 'rules of thumb' for granted. > > Let's just do it rather than speculating: > > require 'benchmark' > > ITERATIONS = 1_000_000 > MAX_INT = 2 ** 30 > NUMS = (1..ITERATIONS).map{ rand(MAX_INT) } > Benchmark.bmbm{ |x| > x.report '(n % 2).zero?' do > NUMS.each{ |n| > (n % 2).zero? > } > end > > x.report 'n[0].zero?' do > NUMS.each{ |n| > n[0].zero? > } > end > > x.report '(n & 1).zero?' do > NUMS.each{ |n| > (n & 1).zero? > } > end > } > > #=> Rehearsal ------------------------------------------------- > #=> (n % 2).zero? 2.060000 0.020000 2.080000 ( 2.244595) > #=> n[0].zero? 1.960000 0.010000 1.970000 ( 2.145238) > #=> (n & 1).zero? 1.990000 0.020000 2.010000 ( 2.275232) > #=> ---------------------------------------- total: 6.060000sec > #=> > #=> user system total real > #=> (n % 2).zero? 2.070000 0.010000 2.080000 ( 2.315105) > #=> n[0].zero? 1.960000 0.020000 1.980000 ( 2.143038) > #=> (n & 1).zero? 1.990000 0.010000 2.000000 ( 2.173120) > > There is a very, very, very small difference in speed. I feel like Alice falling into the rabbit hole. I never thought I would see the day when the difference between a division and a bit test would be reduced to insignificance by other factors. Obviously I started thinking about this (and developing my prejudices) before there were numeric coprocessors. Nice demonstration, BTW. -- Paul Lutus http://www.arachnoid.com