Skip to content

Instantly share code, notes, and snippets.

@stulentsev
Created August 20, 2020 15:54
Show Gist options
  • Save stulentsev/bdfb5c22b641b9dac6e30561dc209e51 to your computer and use it in GitHub Desktop.
Save stulentsev/bdfb5c22b641b9dac6e30561dc209e51 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
require 'set'
sizes = [3, 5, 10, 15, 100]
sizes.each do |size|
Benchmark.ips do |x|
range = 1..size
array = range.to_a
hash = array.each_with_object({}) {|x, memo| memo[x] = x}
set = array.to_set
x.report("Set #{size} elements") { set.include?(rand(range)) }
x.report("Array #{size} elements") { array.include?(rand(range)) }
x.report("Hash #{size} elements" ) { hash.include?(rand(range)) }
x.compare!
end
end
# >> Comparison:
# >> Hash 3 elements: 4652868.0 i/s
# >> Array 3 elements: 4524900.6 i/s - same-ish: difference falls within error
# >> Set 3 elements: 4498189.7 i/s - same-ish: difference falls within error
# >>
# >> Comparison:
# >> Hash 5 elements: 4832112.9 i/s
# >> Set 5 elements: 4639119.4 i/s - 1.04x (± 0.00) slower
# >> Array 5 elements: 4516659.4 i/s - 1.07x (± 0.00) slower
# >>
# >> Comparison:
# >> Hash 10 elements: 4559976.4 i/s
# >> Set 10 elements: 4390093.7 i/s - same-ish: difference falls within error
# >> Array 10 elements: 3925687.9 i/s - 1.16x (± 0.00) slower
# >>
# >> Comparison:
# >> Hash 15 elements: 4535269.1 i/s
# >> Set 15 elements: 4014551.2 i/s - same-ish: difference falls within error
# >> Array 15 elements: 3504591.6 i/s - 1.29x (± 0.00) slower
# >>
# >> Comparison:
# >> Hash 100 elements: 4699044.3 i/s
# >> Set 100 elements: 4307680.6 i/s - same-ish: difference falls within error
# >> Array 100 elements: 1483862.8 i/s - 3.17x (± 0.00) slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment