Skip to content

Instantly share code, notes, and snippets.

@JuanitoFatas
Created February 20, 2015 04:03
Show Gist options
  • Save JuanitoFatas/aa802614a2417d9edb50 to your computer and use it in GitHub Desktop.
Save JuanitoFatas/aa802614a2417d9edb50 to your computer and use it in GitHub Desktop.
Union by Array#&, Set#&, and Set#intersection
require 'benchmark/ips'
X = [5, 5, 1, 1]
Y = [1, 2, 5]
def fast
X & Y
end
def slow
require "set"
Set.new(X) & Set.new(Y)
end
def slowest
require "set"
Set.new(X).intersection Set.new(Y)
end
Benchmark.ips do |x|
x.report('Union by Array#&') { fast }
x.report('Union by Set#&') { slow }
x.report('Union by Set#intersection') { slowest }
x.compare!
end
@JuanitoFatas
Copy link
Author

$ ruby -v union-array-vs-set.rb
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]

Calculating -------------------------------------
    Union by Array#&      73.748k i/100ms
      Union by Set#&       9.078k i/100ms
Union by Set#intersection  8.956k i/100ms
-------------------------------------------------
    Union by Array#&        1.402M (± 7.4%) i/s -      7.006M
      Union by Set#&      100.719k (± 7.5%) i/s -    508.368k
Union by Set#intersection 105.286k (± 4.8%) i/s -    528.404k

Comparison:
    Union by Array#&:        1401564.1 i/s
Union by Set#intersection:    105285.9 i/s - 13.31x slower
      Union by Set#&:         100719.1 i/s - 13.92x slower

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