Kurt Stephens

Nerd Up!

Ruby 1.8: Improved Rational performance by 15%

Kurt on Wed, 2009-12-23 21:27.

This should also speed up DateTime. This will not help 1.9 performance.

The attached file is based on MRI 1.8.6 rational.rb.

 > ruby rational_performance.rb 
                                              user     system      total        real
test_it                                  32.930000   3.030000  35.960000 ( 35.971832)
test_it                                  33.840000   2.910000  36.750000 ( 36.758585)
test_it ks_rational                      29.110000   2.460000  31.570000 ( 31.572762)

Overview:

  • case x; when Foo; ...; end is faster than if Foo.kind_of?(x).
  • Avoid recursing on ephemeral objects.
  • Avoid local variables, in-line expressions.
  • Avoid return in tail position.
  • String interpolation: "#{x}/#{y}" is faster than x.to_s + "/" + y.to_s.
  • Implement #-, #zero?, #nonzero? natively.
  • #abs returns self if > 0.

MRI 1.8.7 patch to follow shortly.


AttachmentSize
ks_rational.rb11.46 KB
rational_performance.rb3.47 KB
links: Kurt's blog | add new comment | 4286 reads

MRI 1.8.7


1.8.7 patch is reported here:

http://redmine.ruby-lang.org/issues/show/2561


$ irb irb(main):001:0>


  $ irb 
  irb(main):001:0> require “ks_rational.rb”
  => true
  irb(main):002:0> r = Rational.new! 0, 0
  => Rational0, 0
  irb(main):003:0> r.zero?
  => true
  irb(main):004:0> r = Rational(0, 0)
  ZeroDivisionError: denominator is zero
      from ks_rational.rb:76:in `reduce’
      from ks_rational.rb:39:in `Rational’
      from (irb):2

I’d suggest a warning in the RDoc for #zero? similar to the one for #==. Rational.new! is voodoo! I’d almost recommend it should be Rational.faux!

Primary links

Syndicate

Syndicate content

Browse archives

« February 2012  
Mo Tu We Th Fr Sa Su
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29