From: Robert Klemme Date: 2005-06-20T22:25:35+09:00 Subject: Re: x==1 vs 1==x Gavin Kistner wrote: > I'm against _premature_ optimization in theory, but believe that a > certain innate knowledge of what is and what is not efficient is > important for making reasonable choices in the first place. > > To that end, when I had to write code to handle exactly one case out > of many, where I knew that the operator would be #==, I thought I'd > test case versus if/elsif. As I expected, the case statement > performed worse (thought not as much as I expected). > > On a whim, I also tested comparing x == 1 separate from 1 == x. Even > when x was a Fixnum, the latter was surprisingly and significantly > slower. Can anyone explain the following results? Yes, probably: you have something else in x than you expect. x is really the benchmark instance and not some Fixnum. :-) Kind regards robert > > 8 > Fixnum > Rehearsal --------------------------------------------- > case 1.500000 0.020000 1.520000 ( 2.249505) > if x==n 0.930000 0.020000 0.950000 ( 1.332420) > if n==x 1.330000 0.020000 1.350000 ( 1.914666) > ------------------------------------ total: 3.820000sec > > user system total real > case 1.510000 0.020000 1.530000 ( 2.343995) > if x==n 0.920000 0.020000 0.940000 ( 1.277303) > if n==x 1.340000 0.020000 1.360000 ( 1.937022) > > > require 'benchmark' > > n = 100_000 > x = rand( 10 ) > p x, x.class > Benchmark.bmbm(10){ |x| > x.report('case'){ > n.times{ > case x > when 0 : 0 > when 1 : 1 > when 2 : 2 > when 3 : 3 > when 4 : 4 > when 5 : 5 > when 6 : 6 > when 7 : 7 > when 8 : 8 > else 9 > end > } > } > x.report('if x==n'){ > n.times{ > if x==0 > 0 > elsif x==1 > 1 > elsif x==2 > 2 > elsif x==3 > 3 > elsif x==4 > 4 > elsif x==5 > 5 > elsif x==6 > 6 > elsif x==7 > 7 > elsif x==8 > 8 > else > 9 > end > } > } > > x.report('if n==x'){ > n.times{ > if 0==x > 0 > elsif 1==x > 1 > elsif 2==x > 2 > elsif 3==x > 3 > elsif 4==x > 4 > elsif 5==x > 5 > elsif 6==x > 6 > elsif 7==x > 7 > elsif 8==x > 8 > else > 9 > end > } > } > }