Created
May 3, 2017 17:23
-
-
Save jaredmoody/d2a1e83de2f91fd6865920cd01a8b497 to your computer and use it in GitHub Desktop.
Benchmark for determining if array contains any member of another array
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/ips' | |
require 'set' | |
puts "ruby version: #{RUBY_VERSION}" | |
CHEESES = %w(chedder stilton brie mozzarella feta haloumi).freeze | |
FOODS = %w(pizza feta foods bread biscuits yoghurt bacon).freeze | |
Benchmark.ips do |b| | |
b.report("&, empty?") { (FOODS & CHEESES).empty? } | |
b.report("any?, include?") { FOODS.any? {|food| CHEESES.include?(food) } } | |
b.report("Set disjoint") { Set.new(CHEESES).disjoint? Set.new(FOODS) } | |
b.compare! | |
end | |
# My results: | |
# | |
# ruby version: 2.2.6 | |
# Warming up -------------------------------------- | |
# &, empty? 42.348k i/100ms | |
# any?, include? 112.146k i/100ms | |
# Set disjoint 7.278k i/100ms | |
# Calculating ------------------------------------- | |
# &, empty? 507.050k (± 6.2%) i/s - 2.541M in 5.032420s | |
# any?, include? 2.125M (± 5.5%) i/s - 10.654M in 5.030139s | |
# Set disjoint 81.391k (± 3.7%) i/s - 407.568k in 5.014699s | |
# | |
# Comparison: | |
# any?, include?: 2125373.3 i/s | |
# &, empty?: 507049.7 i/s - 4.19x slower | |
# Set disjoint: 81390.6 i/s - 26.11x slower | |
# ************************************************************* | |
# ruby version: 2.3.4 | |
# Warming up -------------------------------------- | |
# &, empty? 43.809k i/100ms | |
# any?, include? 135.902k i/100ms | |
# Set disjoint 8.354k i/100ms | |
# Calculating ------------------------------------- | |
# &, empty? 553.701k (± 4.2%) i/s - 2.804M in 5.073096s | |
# any?, include? 2.415M (± 7.0%) i/s - 12.095M in 5.043469s | |
# Set disjoint 79.318k (±10.2%) i/s - 392.638k in 5.013309s | |
# | |
# Comparison: | |
# any?, include?: 2414705.1 i/s | |
# &, empty?: 553700.7 i/s - 4.36x slower | |
# Set disjoint: 79318.2 i/s - 30.44x slower |
davidkovsky
commented
May 4, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment