2

给定以下方法:

def some_hash
  {
    :one => 1,
    :two => 2,
  }
end

记忆散列是否有任何性能优势?

def some_hash
  @some_hash ||= {
    :one => 1,
    :two => 2,
  }
end
4

2 回答 2

4

似乎记忆的变体快了大约 7.5 倍:

def hash1
  {
    :one => 1,
    :two => 2,
  }
end

def hash2
  @some_hash ||= {
    :one => 1,
    :two => 2,
  }
end


require 'benchmark'

Benchmark.bmbm do |b|
  b.report do
    1_000_000.times{ hash1 }
  end
end

Benchmark.bmbm do |b|
  b.report do
    1_000_000.times{ hash2 }
  end
end

 

Rehearsal ------------------------------------
   1.470000   0.030000   1.500000 (  1.499750)
--------------------------- total: 1.500000sec

       user     system      total        real
   1.570000   0.030000   1.600000 (  1.739230)
Rehearsal ------------------------------------
   0.210000   0.000000   0.210000 (  0.231601)
--------------------------- total: 0.210000sec

       user     system      total        real
   0.210000   0.010000   0.220000 (  0.234898)
于 2012-08-31T18:13:34.813 回答
3

编译器/解释器不能自动将第一种形式转换为第二种形式,因为两者等价:

a1, b1 = hash1, hash1
a1[:one] = 'ONE'

a2, b2 = hash2, hash2
a2[:one] = 'ONE'

p b1[:one], b2[:one]
# 1
# 'ONE'

再一次,共享可变状态出现了丑陋的一面。不,孩子们,这不仅仅是关于并发!

于 2012-09-01T01:53:48.497 回答