Skip to content

Instantly share code, notes, and snippets.

@tjschuck
Created November 18, 2015 22:46
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 tjschuck/b3fe4e8c812712376648 to your computer and use it in GitHub Desktop.
Save tjschuck/b3fe4e8c812712376648 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
module Enumerable
def old_sum(identity = 0, &block)
if block_given?
map(&block).old_sum(identity)
else
inject { |sum, element| sum + element } || identity
end
end
def new_sum(identity = 0, &block)
if block_given?
map(&block).new_sum(identity)
else
inject(:+) || identity
end
end
end
summable = (1..100).to_a # sum is 5050
alphabetable = ("a".."z").to_a # sum is the alphabet
Benchmark.ips do |x|
x.report("old_sum") { summable.old_sum }
x.report("new_sum") { summable.new_sum }
x.compare!
end
# Calculating -------------------------------------
# old_sum 10.674k i/100ms
# new_sum 14.542k i/100ms
# -------------------------------------------------
# old_sum 117.350k (± 7.1%) i/s - 587.070k
# new_sum 154.712k (± 3.8%) i/s - 785.268k
#
# Comparison:
# new_sum: 154712.1 i/s
# old_sum: 117350.0 i/s - 1.32x slower
Benchmark.ips do |x|
x.report("old_sum string") { alphabetable.old_sum }
x.report("new_sum string") { alphabetable.new_sum }
x.compare!
end
# Calculating -------------------------------------
# old_sum string 16.197k i/100ms
# new_sum string 16.489k i/100ms
# -------------------------------------------------
# old_sum string 175.858k (±12.7%) i/s - 874.638k
# new_sum string 207.072k (±14.4%) i/s - 1.022M
#
# Comparison:
# new_sum string: 207072.2 i/s
# old_sum string: 175857.9 i/s - 1.18x slower
Benchmark.ips do |x|
x.report("old_sum with block") { summable.old_sum { |i| i * 2 } }
x.report("new_sum with block") { summable.new_sum { |i| i * 2 } }
x.compare!
end
# Calculating -------------------------------------
# old_sum with block 5.315k i/100ms
# new_sum with block 5.984k i/100ms
# -------------------------------------------------
# old_sum with block 54.726k (± 7.5%) i/s - 276.380k
# new_sum with block 60.620k (± 6.8%) i/s - 305.184k
#
# Comparison:
# new_sum with block: 60620.2 i/s
# old_sum with block: 54726.2 i/s - 1.11x slower
Benchmark.ips do |x|
x.report("old_sum string with block") { alphabetable.old_sum { |i| i * 2 } }
x.report("new_sum string with block") { alphabetable.new_sum { |i| i * 2 } }
x.compare!
end
# Calculating -------------------------------------
# old_sum string with block
# 6.604k i/100ms
# new_sum string with block
# 6.790k i/100ms
# -------------------------------------------------
# old_sum string with block
# 69.845k (±19.3%) i/s - 343.408k
# new_sum string with block
# 74.767k (±21.1%) i/s - 359.870k
#
# Comparison:
# new_sum string with block: 74767.3 i/s
# old_sum string with block: 69844.7 i/s - 1.07x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment