Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.