Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick benchmark for .reject with rejected array initialization in loop and out of loop
require "benchmark"
ITEMS = { :foo => "bar", :fizz => "buzz", :fazz => "bazz" }
REJECTED_ITEMS = [:foo, :fazz]
# Number of iterations
@n = 10
def with_constant
@n.times do
ITEMS.reject{|k,v| REJECTED_ITEMS.include?(k) }
end
end
def without_constant
@n.times do
ITEMS.reject{|k,v| [:foo, :fazz].include?(k) }
end
end
Benchmark.bmbm do |x|
x.report { with_constant }
x.report { without_constant }
end
# Test run for n=10
╭─jason@jasons-mbp ~ ‹master›
╰─$ ruby benchmark.rb
Rehearsal ------------------------------------
0.000000 0.000000 0.000000 ( 0.000031)
0.000000 0.000000 0.000000 ( 0.000025)
--------------------------- total: 0.000000sec
user system total real
0.000000 0.000000 0.000000 ( 0.000024)
0.000000 0.000000 0.000000 ( 0.000024)
# Test run for n=1000000
╭─jason@jasons-mbp ~ ‹master›
╰─$ ruby benchmark.rb
Rehearsal ------------------------------------
1.760000 0.030000 1.790000 ( 1.790961)
1.970000 0.020000 1.990000 ( 1.987612)
--------------------------- total: 3.780000sec
user system total real
1.720000 0.030000 1.750000 ( 1.753787)
1.970000 0.010000 1.980000 ( 1.986179)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.