Created
October 23, 2012 11:41
-
-
Save joel/3938318 to your computer and use it in GitHub Desktop.
inject vs reduce
This file contains hidden or 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' | |
class Foo | |
def initialize | |
@bar = rand(100) # for caching | |
end | |
def bar | |
@bar ||= rand(100) | |
end | |
end | |
ARRAY = [].tap { |array| 1000.times { array << Foo.new } } | |
N = 5000 | |
Benchmark.bmbm do |x| | |
x.report('reduce') { N.times { | |
ARRAY.map(&:bar).reduce(:+) | |
} } | |
x.report('inject') { N.times { | |
ARRAY.inject(0){ |sum, entry| sum += entry.bar } | |
} } | |
end | |
# Rehearsal ------------------------------------------ | |
# reduce 4.010000 0.020000 4.030000 ( 4.142364) | |
# inject 3.590000 0.000000 3.590000 ( 3.828996) | |
# --------------------------------- total: 7.620000sec | |
# | |
# user system total real | |
# reduce 3.900000 0.010000 3.910000 ( 3.981650) | |
# inject 3.600000 0.010000 3.610000 ( 3.676255) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment