Skip to content

Instantly share code, notes, and snippets.

@mattknox
Forked from marcel/gist:2957562
Created June 20, 2012 01:32
Show Gist options
  • Save mattknox/2957580 to your computer and use it in GitHub Desktop.
Save mattknox/2957580 to your computer and use it in GitHub Desktop.
require "rubygems"
require "rbench"
require "set"
RANGE = (1..1000)
ARRAY = RANGE.to_a
SET = Set.new(ARRAY)
HASH = ARRAY.inject({}) {|m, x| m[x] = true; m}
WORST_CASE_COMPLEXITY = ARRAY.size + 1
RBench.run(50_000) do
column :one, :title => 'Array'
column :two, :title => 'Set'
column :three, :title => 'Range'
column :four, :title => 'Hash'
report "Which is fastest for misses?" do
one { ARRAY.include?(WORST_CASE_COMPLEXITY) }
two { SET.include?(WORST_CASE_COMPLEXITY) }
three { RANGE.include?(WORST_CASE_COMPLEXITY) }
four { HASH.include?(WORST_CASE_COMPLEXITY) }
end
report "Which is fastest for hits?" do
one { ARRAY.include?(1) }
two { SET.include?(1) }
three { RANGE.include?(1) }
four { HASH.include?(1) }
end
end
__END__
Array | Set | Range | Hash |
----------------------------------------------------------------------------
Which is fastest for misses? 2.237 | 0.016 | 0.016 | 0.009 |
Which is fastest for hits? 0.007 | 0.015 | 0.017 | 0.008 |
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment