Created
February 24, 2012 17:56
-
-
Save chrishunt/1902399 to your computer and use it in GitHub Desktop.
each vs inject vs map
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
Running 100000 iterations... | |
each: 6.872149 | |
inject: 6.868875 | |
map: 0.093785 |
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
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