Created
July 31, 2012 04:58
-
-
Save trans/3213779 to your computer and use it in GitHub Desktop.
Benchmark iteration with index approaches.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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