Skip to content

Instantly share code, notes, and snippets.

@joel
Created October 23, 2012 11:41
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 joel/3938318 to your computer and use it in GitHub Desktop.
Save joel/3938318 to your computer and use it in GitHub Desktop.
inject vs reduce
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