Skip to content

Instantly share code, notes, and snippets.

@angelikatyborska
Created January 30, 2016 16:26
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 angelikatyborska/ed77808bc33043071a31 to your computer and use it in GitHub Desktop.
Save angelikatyborska/ed77808bc33043071a31 to your computer and use it in GitHub Desktop.
A comparison of Ruby's Enumerable#inject and Enumerable#each_with_object
require 'benchmark'
module InjectVsEachWithObject
ARRAY_LENGTH = 10_000
ARRAY = (1..ARRAY_LENGTH).to_a
REPETITIONS = ARGV[0].nil? ? 100 : ARGV[0].to_i
def self.immutable_inject
REPETITIONS.times do
ARRAY.inject(0) { |sum, n| sum + n }
end
end
# DOES NOT WORK (returns 0)
def self.immutable_each_with_object
REPETITIONS.times do
ARRAY.each_with_object(0) { |n, sum| sum += n }
end
end
def self.mutable_inject_plus
REPETITIONS.times do
ARRAY.inject([]) { |new_array, n| new_array + [3 * n] }
end
end
# DOES NOT WORK (returns [])
def self.mutable_each_with_object_plus
REPETITIONS.times do
ARRAY.each_with_object([]) { |n, new_array| new_array += [3 * n]}
end
end
def self.mutable_inject_shovel
REPETITIONS.times do
ARRAY.inject([]) { |new_array, n| new_array << 3 * n }
end
end
def self.mutable_each_with_object_shovel
REPETITIONS.times do
ARRAY.each_with_object([]) { |n, new_array| new_array << 3 * n }
end
end
def self.run
puts 'Running benchmark...'
puts "Summing an array of #{ ARRAY_LENGTH } integers (working with an immutable object) #{ REPETITIONS } times:"
Benchmark.bm(30) do |x|
x.report("inject:") { immutable_inject }
end
puts "Populating an array from another array of #{ ARRAY_LENGTH } integers (working with a mutable object) #{ REPETITIONS } times:"
Benchmark.bm(30) do |x|
x.report("inject (+):") { mutable_inject_plus }
x.report("inject (<<):") { mutable_inject_shovel }
x.report("each_with_object (<<):") { mutable_each_with_object_shovel }
end
end
end
InjectVsEachWithObject.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment