Skip to content

Instantly share code, notes, and snippets.

@rmm5t
Last active June 23, 2019 18:58
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 rmm5t/2338e78d6516360a002616a6693ac8c4 to your computer and use it in GitHub Desktop.
Save rmm5t/2338e78d6516360a002616a6693ac8c4 to your computer and use it in GitHub Desktop.
Benchmark enumerator patterns
require 'benchmark'
array = (1..1000).to_a
n = 1000
Benchmark.bmbm do |x|
x.report("lazy") { n.times { array.lazy.select(&:even?).map { |i| i / 2 }.to_a } }
x.report("double-pass") { n.times { array.select(&:even?).map { |i| i / 2 } } }
x.report("nested conditional") do
n.times do
[].tap do |evens|
array.each do |i|
next unless i.even?
evens << i / 2
end
end
end
end
end
# >>
# >> user system total real
# >> lazy 0.170447 0.000294 0.170741 ( 0.170932)
# >> double-pass 0.060291 0.001461 0.061752 ( 0.061843)
# >> nested conditional 0.055417 0.000347 0.055764 ( 0.055812)
require 'benchmark'
class Tray
def initialize(n)
@active = n % 3 != 1
end
def active?
@active
end
end
tray_count = 5400
trays = []
1.upto(tray_count) do |index|
trays << Tray.new(index)
end
def do_something(tray)
a = 1
a + 1
end
n = 1000
Benchmark.bmbm(15) do |benchmark|
benchmark.report("lazy") do
n.times do
trays.lazy.select(&:active?).each { |t| do_something(t) }
end
end
benchmark.report("double pass") do
n.times do
trays.select(&:active?).each { |t| do_something(t) }
end
end
benchmark.report("nested conditional") do
n.times do
trays.each do |t|
next unless t.active?
do_something(t)
end
end
end
end
# >>
# >> user system total real
# >> lazy 0.948223 0.001460 0.949683 ( 0.950818)
# >> double pass 0.486718 0.003141 0.489859 ( 0.490453)
# >> nested conditional 0.338364 0.000873 0.339237 ( 0.339800)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment