times
is recommended over each_with_index
. times
is around 6 times faster. Run the code below.
require "benchmark"
TESTS = 10_000_000
array = (1..TESTS).map { rand }
Benchmark.bmbm do |results|
results.report("times") do
TESTS.times do |i|
# do nothing
end
end
results.report("each_with_index") do
array.each_with_index do |element, index|
# Do nothing
end
end
end
I got the result as below with my MacBook (Intel Core2Duo).
Rehearsal ---------------------------------------------------
times 1.130000 0.000000 1.130000 ( 1.141054)
each_with_index 7.550000 0.210000 7.760000 ( 7.856737)
------------------------------------------ total: 8.890000sec
user system total real
times 1.090000 0.000000 1.090000 ( 1.099561)
each_with_index 7.600000 0.200000 7.800000 ( 7.888901)