Skip to content

Instantly share code, notes, and snippets.

@jodosha
Created January 30, 2015 14:42
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/ac5dd54416de744b9600 to your computer and use it in GitHub Desktop.
Save jodosha/ac5dd54416de744b9600 to your computer and use it in GitHub Desktop.
Hash vs Set lookup benchmark
#!/usr/bin/env ruby
require 'set'
require 'benchmark/ips'
NON_PRINTABLE_CHARS_HASH = {
0x0 => true,
0x1 => true,
0x2 => true,
0x3 => true,
0x4 => true,
0x5 => true,
0x6 => true,
0x7 => true,
0x8 => true,
0x11 => true,
0x12 => true,
0x14 => true,
0x15 => true,
0x16 => true,
0x17 => true,
0x18 => true,
0x19 => true,
0x1a => true,
0x1b => true,
0x1c => true,
0x1d => true,
0x1e => true,
0x1f => true,
0x7f => true,
0x80 => true,
0x81 => true,
0x82 => true,
0x83 => true,
0x84 => true,
0x85 => true,
0x86 => true,
0x87 => true,
0x88 => true,
0x89 => true,
0x8a => true,
0x8b => true,
0x8c => true,
0x8d => true,
0x8e => true,
0x8f => true,
0x90 => true,
0x91 => true,
0x92 => true,
0x93 => true,
0x94 => true,
0x95 => true,
0x96 => true,
0x97 => true,
0x98 => true,
0x99 => true,
0x9a => true,
0x9b => true,
0x9c => true,
0x9d => true,
0x9e => true,
0x9f => true
}.freeze
NON_PRINTABLE_CHARS = Set.new([0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x11,
0x12, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b,
0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f]).freeze
Benchmark.ips do |x|
x.report('hash') { NON_PRINTABLE_CHARS_HASH[0x9f] }
x.report('set') { NON_PRINTABLE_CHARS.include?(0x9f) }
end
__END__
Calculating -------------------------------------
hash 117.408k i/100ms
set 99.088k i/100ms
-------------------------------------------------
hash 7.790M (± 7.5%) i/s - 38.745M # BEST
set 5.594M (± 6.8%) i/s - 27.844M
Ruby:
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin13]
Hardware:
Hardware Overview:
Model Name: MacBook Air
Model Identifier: MacBookAir5,2
Processor Name: Intel Core i7
Processor Speed: 2 GHz
Number of Processors: 1
Total Number of Cores: 2
L2 Cache (per Core): 256 KB
L3 Cache: 4 MB
Memory: 8 GB
Boot ROM Version: MBA51.00EF.B02
SMC Version (system): 2.5f9
Software:
System Software Overview:
System Version: OS X 10.9.5 (13F34)
Kernel Version: Darwin 13.4.0
Time since boot: 45 days 23:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment