Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tosbourn/c9aacfbd335f15d74453 to your computer and use it in GitHub Desktop.
Save tosbourn/c9aacfbd335f15d74453 to your computer and use it in GitHub Desktop.
require "set"
require 'benchmark/ips'
X = [5, 5, 1, 1]
Y = [1, 2, 5]
SET_X = Set.new(X)
SET_Y = Set.new(Y)
def fast
X & Y
end
def slow
SET_X & SET_Y
end
def slowest
SET_X.intersection SET_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
@tosbourn
Copy link
Author

Calculating -------------------------------------
    Union by Array#&    73.415k i/100ms
      Union by Set#&    23.392k i/100ms
Union by Set#intersection
                        23.274k i/100ms
-------------------------------------------------
    Union by Array#&      1.410M (±10.2%) i/s -      6.974M
      Union by Set#&    289.687k (± 3.2%) i/s -      1.450M
Union by Set#intersection
                        279.034k (± 9.3%) i/s -      1.396M

Comparison:
    Union by Array#&:  1410069.9 i/s
      Union by Set#&:   289686.6 i/s - 4.87x slower
Union by Set#intersection:   279033.8 i/s - 5.05x slower

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