迭代如下所示的哈希:
hash.keys.each do |key|
process_key(key)
end
Run Code Online (Sandbox Code Playgroud)
Rubocop宣称我应该使用:
each_key
Run Code Online (Sandbox Code Playgroud)
代替:
keys.each
Run Code Online (Sandbox Code Playgroud)
keys.each和之间的"关键"区别是each_key什么?
由于性能,Rubocop希望您根据您评估的代码来遵循此要求。使用大型数据集会变得很明显。这是文档:https : //github.com/bbatsov/rubocop/blob/master/manual/cops_performance.md#performancehasheachmethods
我还发现有人编写了一个基准测试此基准:https : //gist.github.com/jodosha/8ca2bee6137be94e9dcb
我对其进行了一些修改并在我的系统上运行:
Warming up --------------------------------------
string each 128.742k i/100ms
string keys 114.523k i/100ms
string each_key 134.279k i/100ms
symbol each 128.838k i/100ms
symbol keys 109.398k i/100ms
symbol each_key 132.021k i/100ms
Calculating -------------------------------------
string each 2.053M (± 4.0%) i/s - 10.299M in 5.026890s
string keys 1.864M (± 1.4%) i/s - 9.391M in 5.039759s
string each_key 2.224M (± 5.5%) i/s - 11.145M in 5.032201s
symbol each 2.082M (± 1.0%) i/s - 10.436M in 5.013145s
symbol keys 1.815M (± 2.1%) i/s - 9.080M in 5.004690s
symbol each_key 2.240M (± 1.9%) i/s - 11.222M in 5.012184s
Comparison:
symbol each_key: 2239720.0 i/s
string each_key: 2224205.1 i/s - same-ish: difference falls within error
symbol each: 2081895.2 i/s - 1.08x slower
string each: 2052884.9 i/s - 1.09x slower
string keys: 1863740.5 i/s - 1.20x slower
symbol keys: 1815131.1 i/s - 1.23x slower
Run Code Online (Sandbox Code Playgroud)
链接方法将比使用内置方法(在这种情况下)要慢,后者使用一个特殊的枚举器完成任务。语言创建者把它放在这里是有原因的,也是它的惯用语。