Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 在散列中迭代键的最快方法_Ruby_Arrays_Hash_Benchmarking - Fatal编程技术网

Ruby 在散列中迭代键的最快方法

Ruby 在散列中迭代键的最快方法,ruby,arrays,hash,benchmarking,Ruby,Arrays,Hash,Benchmarking,我像中一样初始化了一个哈希,并运行了一些基准测试 Benchmark.measure { a = h.keys } #=> 0.010000 0.000000 0.010000 ( 0.019832) Benchmark.measure { a.each { |k| } } #=> 0.060000 0.000000 0.060000 ( 0.057262) Benchmark.measure { h.each { |k, v| } } #=> 0.3

我像中一样初始化了一个哈希,并运行了一些基准测试

Benchmark.measure { a = h.keys }
#=>  0.010000   0.000000   0.010000 (  0.019832)
Benchmark.measure { a.each { |k| } }
#=>  0.060000   0.000000   0.060000 (  0.057262)
Benchmark.measure { h.each { |k, v| } }
#=>  0.320000   0.000000   0.320000 (  0.319768)
Benchmark.measure { h.each_key { |k| } }
#=>  0.310000   0.000000   0.310000 (  0.312656)
Benchmark.measure { h.each_pair { |k, v| } }
#=>  0.330000   0.000000   0.330000 (  0.331452)
我曾认为将散列转换为一组键会更慢,但事实并非如此,而且
每个_键
的性能与
每个
相似。为什么会这样?什么是最好的方法?

看着我可以告诉你两个字:视情况而定。如果您的变量名不是一个明显的散列,那么使用
。每对
都会使它变得明显(因为散列是键值对的集合)。如果您的变量名提到“hash”,那么这是有意义的:
hash.each | key,value |
。做一些类似于
散列的事情是没有意义的。每个| u对都做| k |
当您向每个| u对传递一个块参数时,会使代码看起来很混乱


通过分析Github上的几个页面,我很想得出这样的结论:“最佳方法”是在使用
时。每个
,您都应该将块变量命名为
| key,value |
,这样就可以很明显地看出您正在对哈希进行迭代(块参数会告诉您它是哈希)。当使用
。每个_对
时,对块参数的命名可能会有点含糊不清,比如
我的_键| 1,我的_键| 2 |
,因为。每个_对都表示您正在对哈希进行迭代。这一切都是关于在一周(或一个月)后查看您的代码,并能够立即知道发生了什么。与Python不同,Ruby没有“一种正确的方法”来做某事。

最好的方法是什么?不要担心,因为如果块中有实际的代码,它就不会成为瓶颈。请注意,
a.each{k}
与其他代码有很大的不同:它不返回键,而是返回键值对。我的答案是你想要的吗?