ruby - 为什么有七个对象的新散列比六个长度的散列慢得多?

标签 ruby hash

我发现当我新建一个有七个对象的哈希比六个长度的哈希要慢得多。我知道散列的长度会影响性能。但我不知道为什么七是一个特殊的。

这里是基准代码(Ruby 2.2.3):

require 'benchmark/ips'

Benchmark.ips do |x|
  x.report(5) { { a: 0, b: 1, c: 2, d: 3, e: 4 } }
  x.report(6) { { a: 0, b: 1, c: 2, d: 3, e: 4, f: 5 } }
  x.report(7) { { a: 0, b: 1, c: 2, d: 3, e: 4, f: 5, g: 6 } }
  x.report(8) { { a: 0, b: 1, c: 2, d: 3, e: 4, f: 5, g: 6, h: 7 } }
  x.report(9) { { a: 0, b: 1, c: 2, d: 3, e: 4, f: 5, g: 6, h: 7, i: 8 } }

  x.compare!
end

打击就是结果:

Calculating -------------------------------------
                   5    65.986k i/100ms
                   6    63.966k i/100ms
                   7    30.713k i/100ms
                   8    28.991k i/100ms
                   9    27.115k i/100ms
-------------------------------------------------
                   5      1.243M (± 4.3%) i/s -      6.203M
                   6      1.202M (± 5.3%) i/s -      6.013M
                   7    373.366k (±13.7%) i/s -      1.843M
                   8    351.945k (± 8.8%) i/s -      1.768M
                   9    331.398k (± 8.2%) i/s -      1.654M

Comparison:
                   5:  1243005.5 i/s
                   6:  1202032.4 i/s - 1.03x slower
                   7:   373366.5 i/s - 3.33x slower
                   8:   351945.1 i/s - 3.53x slower
                   9:   331398.3 i/s - 3.75x slower

最佳答案

来自 Hash lookup in Ruby, why is it so fast? :

Ruby manages the size of the bins dynamically. It starts with 11 and as soon as one of the bins has 5 or more elements, the bin size is increased and all hash elements are reallocated to their new corresponding bin.

At some point you pay an exponentially increased time penalty while Ruby resizes the bin pool, but if you think about it, its worth the time since this will keep lookup times and memory usage as low as possible.

这意味着 bin 越多,在 bin 中查找特定键所花费的时间就越少。

希望它有助于理解行为。

关于ruby - 为什么有七个对象的新散列比六个长度的散列慢得多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34156755/

相关文章:

java - 将字符串的 MD5 哈希值的最高 8 个字节视为 long(在 Ruby 中)

php - AS3-PHP-MySQL : Hash user's password in AS3 or PHP?

c - 如何在C中打印另一个函数使用的函数参数?

mysql - SQL - 最大长度255唯一索引 - 哈希解决方案

ruby - 使用 Heroku 存储和处理大型 XML 文件?

mysql - 如何维护数据库中的重复记录?

ruby-on-rails - 页面刷新后在 Ruby on Rails 中获取 Request Referer

ruby - 相当于 Perl 在 Ruby 中的 END block

ruby - 为什么 Ruby 中没有竞争条件

c++ - 部分专用模板的声明不完整