-
-
Save awesome/7ae68776d6c8291d499b79c1440bb9e1 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
This file contains 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' | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment