为什么Array.reverse_each比Array.reverse.each快 [英] Why Array.reverse_each is faster than Array.reverse.each
问题描述
我几乎不使用 reverse_each
方法,而不是我呼吁 reverse.each
,当我需要向后遍历数组。所以,我只是做了一些基准,显然 reverse_each
比 reverse.each
显著更快。
- 这是因为使用时通过它迭代之前创建一个反向阵列相关联的时间元素
reverse.each
?
但在我的例子为1000万次迭代 TIME(反向)+ TIME(每个)(下) - TIME(reverse.each)〜1.2秒
的数组尺寸4.而这个时间差或多或少的住宿稳定不论数组的大小。我测试了它高达100元。
- 此一秒之差的原因是什么?
要求'标杆'数=千万
ARR =(1..4).to_aBenchmark.bm(13)做| X |
x.report(reverse.each){{number.times {arr.reverse.each | X | X} } }
x.report(reverse_each){{number.times {arr.reverse_each | X | X} } }
x.report(反向){number.times {arr.reverse}}
x.report(每){{number.times {arr.each | X | X} } }
结束
我肯定会说,它已与时间建立反向关联数组做的!你只尝试了非常小的数组(100元素的数组仍然是一个小阵)。如果你试图用更大的阵列(例如10K元素),我觉得你真的会发现其中的差别。
I hardly use reverse_each
method, instead I call upon reverse.each
when I need to traverse an array backwards. So I just did some benchmarking and apparently reverse_each
is significantly faster than reverse.each
.
- Is this because there is an element of time associated with creating a reverse array before iterating through it when using
reverse.each
?
However in my example (below) of 10 million iterations TIME(reverse) + TIME(each) - TIME(reverse.each) ~ 1.2 seconds
for an array of size 4. And this time difference more or less stays stable irrespective of the size of array. I have tested it for upto 100 elements.
- What accounts for this one second difference?
require 'benchmark'
number = 10000000
arr = (1..4).to_a
Benchmark.bm(13) do |x|
x.report("reverse.each") { number.times { arr.reverse.each {|x| x} } }
x.report("reverse_each") { number.times { arr.reverse_each {|x| x} } }
x.report("reverse") { number.times { arr.reverse } }
x.report("each") { number.times { arr.each {|x| x} } }
end
I would definitely say it has to do with the time associating with creating the reverse array! You've only tried really small arrays (an array with 100 elements is still a small array). If you try with bigger arrays (for instance 10k elements), I think you will really notice the difference.
这篇关于为什么Array.reverse_each比Array.reverse.each快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!