Skip to content

Instantly share code, notes, and snippets.

@jballanc
Created September 5, 2011 20:54
Show Gist options
  • Save jballanc/1195890 to your computer and use it in GitHub Desktop.
Save jballanc/1195890 to your computer and use it in GitHub Desktop.
Set#include? vs Hash#include? vs Hash#[]
require 'benchmark'
require 'set'
[10000, 100000, 1000000].each do |length|
Benchmark.bmbm do |x|
a = (1..length).to_a
s = Set.new(a)
h = Hash[a.zip([true]*a.length)]
puts "\n\nSearching through #{length} elements"
x.report('Set#include?') { 10000000.times { s.include? rand(200) } }
x.report('Hash#include?') { 10000000.times { h.include? rand(200) } }
x.report('Hash#[]') { 10000000.times { h[rand(200)] } }
end
end
Searching through 10000 elements
Rehearsal -------------------------------------------------
Set#include? 4.510000 0.000000 4.510000 ( 4.521795)
Hash#include? 3.930000 0.010000 3.940000 ( 3.939783)
Hash#[] 3.610000 0.000000 3.610000 ( 3.627755)
--------------------------------------- total: 12.060000sec
user system total real
Set#include? 4.520000 0.010000 4.530000 ( 4.529696)
Hash#include? 3.910000 0.010000 3.920000 ( 3.918378)
Hash#[] 3.570000 0.000000 3.570000 ( 3.579173)
Searching through 100000 elements
Rehearsal -------------------------------------------------
Set#include? 4.490000 0.010000 4.500000 ( 4.500315)
Hash#include? 3.860000 0.010000 3.870000 ( 3.865276)
Hash#[] 3.540000 0.000000 3.540000 ( 3.560600)
--------------------------------------- total: 11.910000sec
user system total real
Set#include? 4.500000 0.020000 4.520000 ( 4.594239)
Hash#include? 3.860000 0.030000 3.890000 ( 4.365213)
Hash#[] 3.560000 0.010000 3.570000 ( 3.653756)
Searching through 1000000 elements
Rehearsal -------------------------------------------------
Set#include? 4.700000 0.000000 4.700000 ( 4.710997)
Hash#include? 4.190000 0.010000 4.200000 ( 4.206315)
Hash#[] 3.780000 0.010000 3.790000 ( 3.784912)
--------------------------------------- total: 12.690000sec
user system total real
Set#include? 4.690000 0.010000 4.700000 ( 4.709617)
Hash#include? 4.130000 0.010000 4.140000 ( 4.142423)
Hash#[] 3.740000 0.000000 3.740000 ( 3.742781)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment