Kurt Stephens

Nerd Up!

Kurt 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 nicey_cached_foo “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.


links: read more | Kurt's blog | add new comment | 1233 reads

Reply

Please solve the math problem above and type in the result. e.g. for 1+1, type 2
The content of this field is kept private and will not be shown publicly.

Primary links

Syndicate

Syndicate content

Browse archives

« May 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 30 31