Skip to content

Instantly share code, notes, and snippets.

@chrishunt
Created February 24, 2012 17:56
Show Gist options
  • Save chrishunt/1902399 to your computer and use it in GitHub Desktop.
Save chrishunt/1902399 to your computer and use it in GitHub Desktop.
each vs inject vs map
Running 100000 iterations...
each: 6.872149
inject: 6.868875
map: 0.093785
ITERATIONS = 100000
puts "Running #{ITERATIONS} iterations...\n"
def time(&block)
start = Time.now
block.call
puts Time.now - start
end
time do
text = ''
1.upto(ITERATIONS).each { |i| text += "#{i} " }
print "each:\t"
end
time do
1.upto(ITERATIONS).inject(''){ |text, i| text += "#{i} " }
print "inject:\t"
end
time do
'' + 1.upto(ITERATIONS).map { |i| i }.join(' ')
print "map:\t"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment