Skip to content

Instantly share code, notes, and snippets.

@jrunning
Last active June 5, 2017 16:33
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 jrunning/33e5168306e4b51aa41a6df7458827b2 to your computer and use it in GitHub Desktop.
Save jrunning/33e5168306e4b51aa41a6df7458827b2 to your computer and use it in GitHub Desktop.
require "benchmark/ips"
A_SIZE_RANGE = 0..1000
B_SIZE_RANGE = 2..5
VAL_RANGE = 0...10000
def a
Array.new(rand A_SIZE_RANGE) { rand VAL_RANGE }
end
def b
Array.new(rand B_SIZE_RANGE) { rand VAL_RANGE }
end
Benchmark.ips do |x|
x.report("(a&b).any?") { (a & b).any? }
x.report("a.any? {|item| b.include?(item) }") { a.any? {|item| b.include?(item) } }
x.compare!
end
$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
$ ruby 01_intersect_benchmark.rb
Warming up --------------------------------------
(a&b).any? 839.000 i/100ms
b.any? {|item| a.include?(item) } 267.000 i/100ms
Calculating -------------------------------------
(a&b).any? 8.310k (± 6.4%) i/s - 41.950k in 5.073744s
b.any? {|item| a.include?(item) } 2.731k (± 5.2%) i/s - 13.617k in 5.000863s
Comparison:
(a&b).any?: 8310.2 i/s
b.any? {|item| a.include?(item) }: 2731.1 i/s - 3.04x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment