Kurt StephensNerd Up! | ||
Ruby : Tight Code, Floppy PerformanceKurt on Tue, 2007-10-09 20:04.
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
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. |
||
Recent comments
6 days 2 hours ago
3 weeks 1 day ago
3 weeks 1 day ago
6 weeks 3 days ago
6 weeks 3 days ago
8 weeks 2 days ago
8 weeks 6 days ago
8 weeks 6 days ago
8 weeks 6 days ago
27 weeks 17 hours ago