本文介绍了哈希“ has_key” Ruby中的复杂性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个哈希 vars = { a => 名称, b => 地址, c => 电话} 。我要检查此行的性能:

I have a hash vars = {"a" => "Name", "b" => "Address" , "c" => "Phone"}. I want to check the performance of this line :

vars.has_key(:b)?

是O(1)还是O(哈希大小)?

Is it O(1) or O(size of hash) ?

推荐答案

简单基准测试:

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实施情况下)。

So yes, I think we can consider the cost constant O(1) (at least, without check the internal MRI implementation).

这篇关于哈希“ has_key” Ruby中的复杂性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 13:46