Ruby : Tight Code, Floppy Performance
Posted in News by CM8295.Com on the 2007-10-22
So you’re coding some ruby, and you do the obligatory caching of a computation:
def foo(x)
666
end
$cache = nil
def cryptic_cached_foo
($cache ||= [ foo("bar") ]).first
end
def nicey_cached_foo
unless $cache
$cache = [ foo("bar") ]
end
$cache.first
end
A discussion came up at work: is nicey_cached_foo is “better” than cryptic_cached_foo? Obviously, nicey_cached_foo is more readable, but when I find myself doing the same pattern over and over, I prefer the terse cryptic_cached_foo. I expected cryptic_cached_foo to be faster. Oh boy, was I wrong….
require 'benchmark'
def foo(x)
666
end
def cryptic_cached_foo
($cache ||= [ foo("bar") ]).first
end
def nicey_cached_foo
unless $cache
$cache = [ foo("bar") ]
end
$cache.first
end
n = 100000
Benchmark.bm(10) do | m |
GC.enable
GC.start
GC.disable
m.report("cryptic") do
$cache = nil
n.times do
cryptic_cached_foo()
end
end
GC.enable
GC.start
GC.disable
m.report("nicey") do
$cache = nil
n.times do
nicey_cached_foo()
end
end
end
Test results:
> ~/local/ruby/1.8.6/bin/ruby caching_pattern.rb
user system total real
cryptic 0.116667 0.000000 0.116667 ( 0.070322)
nicey 0.083333 0.000000 0.083333 ( 0.047767)
WTF? Now with ruby 1.9 SVN trunk (YARV):
> ~/local/ruby/trunk/bin/ruby caching_pattern.rb
user system total real
cryptic 0.030000 0.000000 0.030000 ( 0.039227)
nicey 0.030000 0.000000 0.030000 ( 0.037591)
Ahh, now I can sleep tonight.
WidgetBucks - Trend Watch - WidgetBucks.com

Responses to “Ruby : Tight Code, Floppy Performance”