Last active
October 8, 2023 07:58
-
-
Save rsiddle/a87df54191b6b9dfe7c9 to your computer and use it in GitHub Desktop.
Hash vs. Array vs. Set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
require 'set' | |
Document = Struct.new(:id,:a,:b,:c) | |
documents_a = [] | |
documents_h = {} | |
documents_s = Set.new | |
1.upto(10_000) do |n| | |
d = Document.new(n) | |
documents_a << d | |
documents_h[d.id] = d | |
documents_s << d | |
end | |
searchlist = Array.new(1000){ rand(10_000)+1 } | |
Benchmark.bm(10) do |x| | |
x.report('array') {searchlist.each{|el| documents_a.any?{|d| d.id == el}} } | |
x.report('hash') {searchlist.each{|el| documents_h.has_key?(el)} } | |
x.report('set') {searchlist.each{|el| documents_s.include?(el)} } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment