LoginSignup
9
9

More than 5 years have passed since last update.

ruby の Hash#shift が遅い

Posted at

ruby2.0 の Hash クラスを queue として使おうと思い、shift の代わりに first + delete という処理をしていた。

しかし、Hash#shift があることに気づき、なーんだこれ使えばいいのかと思ったものの、Hash#shift に置き換えたら遅かった。

で。どれくらい遅いかという話。

require "benchmark"

def test_shift(size)
  data=Hash[ size.times.map{ |a| [a,a] } ]
  Benchmark.realtime{
    while( size/2 < data.size ) do
      data.shift
    end
  }
end

def shift(v)
  return nil if v.empty?
  a=v.first[0]
  b=v.delete(a)
  [a,b]
end

def test_myshift(size)
  data=Hash[ size.times.map{ |a| [a,a] } ]
  Benchmark.realtime{
    while( size/2 < data.size ) do
      shift(data)
    end
  }
end

R=(10..16)
puts R.map{ |s| "%.4f" % test_shift( 1<<s ) }.join(",")
#=> 0.0016,0.0080,0.0360,0.1718,0.8168,3.5163,14.7884

puts R.map{ |s| "%.4f" % test_myshift( 1<<s ) }.join(",")
#=> 0.0004,0.0008,0.0015,0.0031,0.0064,0.0205,0.0246

ご覧のとおり、6万要素ぐらいあると、自前の実装の shift よりも500倍ぐらい遅い。

なにか見落としている気もするんだけど、どうなんだろ。

9
9
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9