我有一个hashvars = {"a" => "Name", "b" => "Address" , "c" => "Phone"}。我想检查一下这一行的性能:

vars.has_key(:b)?

是o(1)还是o(散列大小)?

最佳答案

简单基准:

require 'benchmark'

iterations = 10_000
small      = 10
big        = 1_000_000

small_hash = {}
big_hash   = {}

(1..small).each do |i|
  small_hash[i] = i
end

(1..big).each do |i|
  big_hash[i] = i
end

Benchmark.bmbm do |bm|
  bm.report('Small Hash') do
    iterations.times { small_hash.has_key?(1) }
  end

  bm.report('Big Hash') do
    iterations.times { big_hash.has_key?(1) }
  end
end

运行测试:
$ ruby has_key_test.rb
                 user     system      total        real
Small Hash   0.000000   0.000000   0.000000 (  0.001167)
Big Hash     0.000000   0.000000   0.000000 (  0.001171)

所以是的,我认为我们可以考虑成本常数o(1)(至少,不检查内部的mri实现)。

10-04 22:25
查看更多