Por qué Array.reverse_each es más rápido que Array.reverse.each
Apenas usoreverse_each
método, en su lugar invocoreverse.each
cuando necesito atravesar una matriz hacia atrás. Así que acabo de hacer un benchmarking y al parecerreverse_each
es significativamente más rápido quereverse.each
.
reverse.each
?Sin embargo en mi ejemplo (abajo) de 10 millones de iteraciones.TIME(reverse) + TIME(each) - TIME(reverse.each) ~ 1.2 seconds
para una matriz de tamaño 4. Y esta diferencia de tiempo se mantiene más o menos estable independientemente del tamaño de la matriz. Lo he probado para hasta 100 elementos.
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