Skip to content

Instantly share code, notes, and snippets.

@leonid-shevtsov
Last active October 3, 2018 05:12
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 leonid-shevtsov/a8976d9b5fc9d9a3a3811ed5c08f660e to your computer and use it in GitHub Desktop.
Save leonid-shevtsov/a8976d9b5fc9d9a3a3811ed5c08f660e to your computer and use it in GitHub Desktop.
require 'set'
require 'benchmark/ips'
Benchmark.ips do |x|
array = (1..50000).to_a
shuffled_array = array.shuffle
set = array.to_set
hash = array.zip([false]*50000).to_h
x.report("with array") { array.include?(Random.rand(50000)) }
x.report("with shuffled array") { shuffled_array.include?(Random.rand(50000)) }
x.report("with set") { set.include?(Random.rand(50000)) }
x.report("with hash") { hash.key?(Random.rand(50000)) }
x.compare!
end
# Comparison:
# with hash: 5585344.2 i/s
# with set: 5183356.5 i/s - same-ish: difference falls within error
# with array: 6322.8 i/s - 883.36x slower
# with shuffled array: 6292.9 i/s - 887.56x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment