Ruby Hash Assignment Performance

最近遇到ruby在處理大量資料時效能低落時順便想到這個問題

用hash在大量insert array的時候做分類,怎麼樣寫會比較快

發現從hash裡面取值出來的次數越少,效能看起來越高

下面是幾個想到的用法,最後一組是直接開固定的key比較沒彈性

倒數第二組則是兼具自動建key和效能的選擇

require 'benchmark'

Benchmark.measure do
  q = {}
  30_000_000.times do
    q['a'] = q['a'] || []
    q['a'] << 2
  end
end
#=> 5.08s

Benchmark.measure do
  q = {}
  30_000_000.times do
    q['a'] ||= []
    q['a'] << 2
  end
end
#=> 4.4s

Benchmark.measure do
  q = {}
  30_000_000.times do
    w = q['a']
    if w.nil?
      w = []
      q['a'] = w
    end
    q['a'] << 2
  end
end
#=> 3.89s

Benchmark.measure do
  q = {}
  30_000_000.times do
    if q['a'].nil?
      q['a'] = []
    end
    q['a'] << 2
  end
end
#=> 3.79s

Benchmark.measure do
  q = {}
  30_000_000.times do
    w = q['a']
    if w.nil?
      w = []
      q['a'] = w
    end
    w << 2
  end
end
#=> 2.53s

Benchmark.measure do
  q = {'a' => []}
  30_000_000.times do
    q['a'] << 2
  end
end
#=> 2.24s

留言

粗體斜體刪除線連結引用圖片程式碼

注意:您的電子信箱將不會被公開,且網站連結不會被搜尋引擎採計