为什么在实例变量中存储值比查找哈希更昂贵?

时间:2014-08-06 11:33:06

标签: ruby performance memoization

我运行了一个基准测试,以查看memoizing属性是否比从配置哈希中读取更快。下面的代码就是一个例子。任何人都可以解释一下吗?

测试

require 'benchmark'

class MyClassWithStuff
  DEFAULT_VALS = { one: '1', two: 2, three: 3, four: 4 }
  def memoized_fetch
    @value ||= DEFAULT_VALS[:one]
  end
  def straight_fetch
    DEFAULT_VALS[:one]
  end
end

TIMES = 10000
CALL_TIMES = 1000

Benchmark.bmbm do |test|
  test.report("Memoized") do
    TIMES.times do
      instance = MyClassWithStuff.new
      CALL_TIMES.times { |i| instance.memoized_fetch }
    end
  end
  test.report("Fetched") do
    TIMES.times do
      instance = MyClassWithStuff.new
      CALL_TIMES.times { |i| instance.straight_fetch }      
    end
  end
end

结果

Rehearsal --------------------------------------------
Memoized   1.500000   0.010000   1.510000 (  1.510230)
Fetched    1.330000   0.000000   1.330000 (  1.342800)
----------------------------------- total: 2.840000sec

               user     system      total        real
Memoized   1.440000   0.000000   1.440000 (  1.456937)
Fetched    1.260000   0.000000   1.260000 (  1.269904)

0 个答案:

没有答案