Last active
March 9, 2017 21:47
-
-
Save MaxPleaner/68a4cbe2679cac86682f3446bd05f460 to your computer and use it in GitHub Desktop.
benchmark comparison of Sets vs Hashes
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
N = 10000000 | |
SET INSERTION: | |
user system total real | |
13.080000 0.370000 13.450000 ( 13.453529) | |
HASH INSERTION: | |
user system total real | |
12.870000 0.330000 13.200000 ( 13.193739) | |
SET DELETION: | |
user system total real | |
9.700000 0.000000 9.700000 ( 9.703152) | |
HASH DELETION: | |
user system total real | |
8.300000 0.000000 8.300000 ( 8.306903) | |
[Finished in 45.3s] |
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
# Sets are like Hashes without significant values | |
# One would hope that deletion by key would be constant-time, like in hashes. | |
# This benchmark investigates that. | |
require 'benchmark' | |
require 'set' | |
NUM = 10_000_000 | |
def bench(&blk) | |
Benchmark.bm { |bm| bm.report &blk } | |
end | |
def set_insertion | |
NUM.times.reduce Set.new, &:<< | |
end | |
def hash_insertion | |
NUM.times.each_with_object(Hash.new) { |n, hash| hash[n] = true } | |
end | |
def set_deletion(set) | |
set.tap { NUM.times.each { |n| set.delete n } } | |
end | |
def hash_deletion(hash) | |
hash.tap { NUM.times.each { |n| hash.delete n } } | |
end | |
puts "\nN = #{NUM}\n" | |
puts "SET INSERTION:\n" | |
bench { @set = set_insertion } | |
puts "HASH INSERTION:\n" | |
bench { @hash = hash_insertion } | |
puts "SET DELETION:\n" | |
bench { set_deletion(@set) } | |
puts "HASH DELETION:\n" | |
bench { set_deletion(@hash) } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment