Skip to content

Instantly share code, notes, and snippets.

@shanna
Forked from tenderlove/inject_test.rb
Created December 15, 2009 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shanna/256662 to your computer and use it in GitHub Desktop.
Save shanna/256662 to your computer and use it in GitHub Desktop.
require 'benchmark'
def each_acc list
foos = []
list.each do |letter|
foos << letter.to_i
end
foos
end
def inject_acc list
list.inject([]) do |memo, item|
memo << item.to_i
end
end
def map_acc list
list.map do |letter|
letter.to_i
end
end
n = 50000
LIST = ('a'..'z').to_a
Benchmark.bm(7) do |x|
x.report('each') do
n.times { each_acc(LIST) }
end
x.report('inject') do
n.times { inject_acc(LIST) }
end
x.report('map') do
n.times { map_acc(LIST) }
end
end
user system total real
each 0.230000 0.060000 0.290000 ( 0.287954)
inject 0.280000 0.010000 0.290000 ( 0.290604)
map 0.170000 0.050000 0.220000 ( 0.227556)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment