Skip to content

Instantly share code, notes, and snippets.

@trans
Created Jul 31, 2012
Embed
What would you like to do?
Benchmark iteration with index approaches.
require 'benchmark'
# Each
Benchmark.bmbm do |x|
n = 1000000
a = ('a'..'z').to_a
x.report("each") do
n.times { a.each{ |e| e } }
end
x.report("enumerator each") do
n.times { a.each.each{ |e| e } }
end
x.report("each_with_index") do
n.times { a.each_with_index{ |e,i| e; i } }
end
x.report("each and manual index") do
n.times { i=0; a.each{ |e| e; i+=1 } }
end
x.report("enumerator each.with_index") do
n.times { a.each.with_index{ |e,i| e; i } }
end
x.report("enumerator each and manual index") do
n.times { i=0; a.each.each{ |e| e; i+=1 } }
end
end
puts
# Map
Benchmark.bmbm do |x|
n = 1000000
a = ('a'..'z').to_a
x.report("map") do
n.times { a.map{ |e| e } }
end
x.report("enumerator map") do
n.times { a.each.map{ |e| e } }
end
x.report("map and manual index") do
n.times { i=0; a.map{ |e| e; i+=1 } }
end
x.report("enumerator map.with_index") do
n.times { a.map.with_index{ |e, i| e; i } }
end
x.report("enumerator map and manual index") do
n.times { i=0; a.each.map{ |e| e; i+=1 } }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment