Skip to content

Instantly share code, notes, and snippets.

@colindean
Created November 24, 2014 00:35
Show Gist options
  • Save colindean/35754385ea3057cd962e to your computer and use it in GitHub Desktop.
Save colindean/35754385ea3057cd962e to your computer and use it in GitHub Desktop.
A simple benchmark of array v hash v set in Ruby
require 'benchmark'
require 'set'
ranges = [ "a".."z", "A".."Z", 0..9 ]
n = ARGV[0].to_i || 100
Benchmark.bm do |x|
#array
x.report "array" do
n.times do
array = []
ranges.each do |range|
range.each do |r|
array[r.to_i] = 0
end
end
end
end
#hash
x.report "hash" do
n.times do
hash = {}
ranges.each do |range|
range.each do |r|
hash[r] = 0
end
end
end
end
#set
x.report "set" do
n.times do
set = Set.new
ranges.each do |range|
range.each do |r|
set.add r.to_i
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment