Skip to content

Instantly share code, notes, and snippets.

@jodosha
Created November 17, 2017 18:55
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 jodosha/743d5c8672ec8d90358f7cbc50f39806 to your computer and use it in GitHub Desktop.
Save jodosha/743d5c8672ec8d90358f7cbc50f39806 to your computer and use it in GitHub Desktop.
Ruby: Hash#key? vs Set#include?
#!/usr/bin/env ruby
require 'benchmark/ips'
require 'set'
SET = (4..16).to_set.freeze
HASH = SET.each_with_object({}) { |n, ret| ret[n] = true }.freeze
Benchmark.ips do |x|
x.report('set') { SET.include?(16) }
x.report('hash') { HASH.key?(16) }
x.compare!
end
__END__
Result:
Warming up --------------------------------------
set 258.952k i/100ms
hash 259.803k i/100ms
Calculating -------------------------------------
set 7.528M (± 3.5%) i/s - 37.807M in 5.028587s
hash 8.746M (± 3.8%) i/s - 43.907M in 5.027637s
Comparison:
hash: 8746234.6 i/s
set: 7528076.7 i/s - 1.16x slower
Ruby:
ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin16]
Hardware:
Hardware Overview:
Model Name: MacBook Pro
Model Identifier: MacBookPro12,1
Processor Name: Intel Core i7
Processor Speed: 3,1 GHz
Number of Processors: 1
Total Number of Cores: 2
L2 Cache (per Core): 256 KB
L3 Cache: 4 MB
Memory: 16 GB
Boot ROM Version: MBP121.0171.B00
SMC Version (system): 2.28f7
Software:
System Software Overview:
System Version: macOS 10.12.6 (16G1036)
Kernel Version: Darwin 16.7.0
Time since boot: 8 days 9:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment