Skip to content

Instantly share code, notes, and snippets.

@ChrisLundquist
Last active December 9, 2015 23:31
Show Gist options
  • Save ChrisLundquist/d06b6cdf1c208d2e7f18 to your computer and use it in GitHub Desktop.
Save ChrisLundquist/d06b6cdf1c208d2e7f18 to your computer and use it in GitHub Desktop.
$ ruby -v
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin14]
Rehearsal --------------------------------------------------------------
map_compact 0.020000 0.000000 0.020000 ( 0.015315)
map_inplace_compact 0.010000 0.000000 0.010000 ( 0.016069)
reject_map 0.010000 0.000000 0.010000 ( 0.014038)
reject_inplace_map 0.860000 0.010000 0.870000 ( 0.860999)
reject_map_inplace 0.010000 0.000000 0.010000 ( 0.013710)
reject_inplace_map_inplace 0.860000 0.000000 0.860000 ( 0.866945)
----------------------------------------------------- total: 1.780000sec
user system total real
map_compact 0.010000 0.000000 0.010000 ( 0.012554)
map_inplace_compact 0.010000 0.000000 0.010000 ( 0.012114)
reject_map 0.010000 0.000000 0.010000 ( 0.021661)
reject_inplace_map 0.850000 0.000000 0.850000 ( 0.855091)
reject_map_inplace 0.010000 0.000000 0.010000 ( 0.015349)
reject_inplace_map_inplace 0.870000 0.000000 0.870000 ( 0.876531)
#!/usr/bin/env ruby
require 'benchmark'
def data
(0...100_000).to_a
end
def map_compact
data.map do |i|
next if i.odd?
i + i
end.compact
end
def map_inplace_compact
data.map! do |i|
next if i.odd?
i + i
end.compact
end
def reject_map
data.reject { |i| i.odd? }.map { |i| i + i }
end
def reject_inplace_map
data.reject! { |i| i.odd? }.map { |i| i + i }
end
def reject_inplace_map_inplace
data.reject! { |i| i.odd? }.map! { |i| i + i }
end
def reject_map_inplace
data.reject { |i| i.odd? }.map! { |i| i + i }
end
Benchmark.bmbm do |x|
x.report("map_compact") { map_compact }
x.report("map_inplace_compact") { map_inplace_compact }
x.report("reject_map") { reject_map }
x.report("reject_inplace_map") { reject_inplace_map }
x.report("reject_map_inplace") { reject_map_inplace }
x.report("reject_inplace_map_inplace") { reject_inplace_map_inplace }
end
@ChrisLundquist
Copy link
Author

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