Skip to content

Instantly share code, notes, and snippets.

@mjgiarlo
Last active June 28, 2016 16:04
Show Gist options
  • Save mjgiarlo/7680957 to your computer and use it in GitHub Desktop.
Save mjgiarlo/7680957 to your computer and use it in GitHub Desktop.
Ruby inject vs. tap vs. each_with_object. Inspired by http://phrogz.net/tap-vs-each_with_object
require 'benchmark'
N = 1000000
nums = N.times.map{ rand(N) }
enum = [1, 2, 'string', {}, [], false, true, nil]
def process(v)
v
end
def i_want_this?(v)
!v.nil?
end
Benchmark.bmbm do |x|
x.report('inj') { enum.inject([]) { |arr, v| arr << process(v) if i_want_this?(v); arr } }
x.report('tap') { [].tap { |arr| enum.each { |v| arr << process(v) if i_want_this?(v) } } }
x.report('ewo') { enum.each_with_object([]) { |v, arr| arr << process(v) if i_want_this?(v) } }
x.report('sel') { enum.select {|v| i_want_this?(v) }.map { |v| process(v) } }
x.report('map') { enum.map { |v| process(v) if i_want_this?(v) }.reject { |v| !v } }
end
# Rehearsal ---------------------------------------
# inj 0.000000 0.000000 0.000000 ( 0.000027)
# tap 0.000000 0.000000 0.000000 ( 0.000017)
# ewo 0.000000 0.000000 0.000000 ( 0.000023)
# sel 0.000000 0.000000 0.000000 ( 0.000016)
# map 0.000000 0.000000 0.000000 ( 0.000021)
# ------------------------------ total: 0.000000sec
#
# user system total real
# inj 0.000000 0.000000 0.000000 ( 0.000025)
# tap 0.000000 0.000000 0.000000 ( 0.000024)
# ewo 0.000000 0.000000 0.000000 ( 0.000026)
# sel 0.000000 0.000000 0.000000 ( 0.000023)
# map 0.000000 0.000000 0.000000 ( 0.000024)
@billdueber
Copy link

The takeaway, obviously, is that you can hardly measure the time of any of them with a million iterations so it doesn't really matter. I tried using an array of 800 elements, too, and got nothing any different.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment