-
-
Save mbklein/7681938 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env ruby | |
require 'benchmark' | |
N = 10000000 | |
vals = [1, 2, 'string', {}, [], false, true, nil] | |
enum = N.times.map { vals[rand(vals.length-1)] } | |
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 8.020000 0.030000 8.050000 ( 8.310335) | |
# tap 6.800000 0.040000 6.840000 ( 7.087833) | |
# ewo 8.360000 0.050000 8.410000 ( 8.763888) | |
# sel 8.700000 0.080000 8.780000 ( 8.858959) | |
# map 8.800000 0.070000 8.870000 ( 9.288306) | |
# ----------------------------- total: 40.950000sec | |
# | |
# user system total real | |
# inj 8.350000 0.050000 8.400000 ( 8.785699) | |
# tap 6.880000 0.040000 6.920000 ( 7.301747) | |
# ewo 7.900000 0.040000 7.940000 ( 8.359985) | |
# sel 8.940000 0.010000 8.950000 ( 9.086054) | |
# map 10.000000 0.050000 10.050000 ( 10.510230) |
adjam
commented
Nov 27, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment