From: "Simon Kröger" Date: 2006-01-06T06:17:56+09:00 Subject: Re: [SUMMARY] Numeric Maze (#60) Lou Vanek wrote: > The shift operator comes in handy and can save a lot of time. > These are equivalent operations: > > >time ruby -e '1_000_000.times { || 2**31 }' > > real 0m33.225s > user 0m32.452s > sys 0m0.015s > >time ruby -e '1_000_000.times { || 1<<31 }' > > real 0m3.469s > user 0m3.421s > sys 0m0.000s > >time ruby -e '1_000_000.times { || > 2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2*2 }' > > real 0m13.839s > user 0m13.656s > sys 0m0.015s > > > Kero wrote: This is an implementation detail, the ** operator of Fixnum calls rb_big_pow converting self to a Bignum regardless of the value. '<<' checks the size of the result and uses real bitshifting if possible. While this was interresting to me it's not the explanation of the effect above because the value 2**31 is always a bignum, but the implementation of the ** operator in Bignum isn't very fast (while shifting the internal representation of the bignum is faster) To prove my point that this isn't realy because bitshifts are faster try this: 1_000_000.times { || 2.0**30 } At least on my machine this is faster than any of your three examples above. (if you choose smaller values '<<' will be the fastest because it doesn't convert to bignums as stated above) cheers Simon