Skip to content

Instantly share code, notes, and snippets.

@radarek
Created January 29, 2014 00:05
Show Gist options
  • Save radarek/8679160 to your computer and use it in GitHub Desktop.
Save radarek/8679160 to your computer and use it in GitHub Desktop.
require 'benchmark'
# [ 1, 2, 3, ..., 10_000 ]
array = (1..10000).to_a
# { 1=>1, 2=>2, ..., 10_000=>10_000 }
hash = Hash[(0..9999).zip(1..10000)]
LOOPS = 1000
Benchmark.bm(10) do |bm|
bm.report('array') do
LOOPS.times do
10_000.times {|i| array[i] }
end
end
bm.report('hash') do
LOOPS.times do
10_000.times {|i| hash[i] }
end
end
end
$ ruby -v
ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-darwin11.0]
$ ruby bm1.rb
user system total real
array 1.060000 0.000000 1.060000 ( 1.108306)
hash 1.920000 0.010000 1.930000 ( 2.006488)
require 'benchmark'
# [ 1, 2, 3, ..., 10_000 ]
array = (1..10000).to_a
# { 1=>1, 2=>2, ..., 10_000=>10_000 }
hash = Hash[(1..10000).zip(1..10000)]
values = (1..10000).to_a
Benchmark.bm(10) do |bm|
bm.report('array') do
values.each do |val|
array.index.each do |index|
break if array[index] == val
end
end
end
bm.report('hash') do
values.each do |val|
hash.keys.each do |key|
break if hash[key] == val
end
end
end
end
$ ruby bm2.rb
user system total real
array 6.090000 0.030000 6.120000 ( 6.495695)
hash 11.850000 0.760000 12.610000 ( 13.343245)
require 'benchmark'
array = (1..10000).map { rand(1_000_000) }
# odwrotny index
hash = Hash[array.each_with_index.to_a.map(&:reverse)]
LOOPS = 10_000
Benchmark.bm(10) do |bm|
bm.report('array') do
LOOPS.times do
array.find_index(rand(1_000_000))
end
end
bm.report('hash') do
LOOPS.times do
hash[rand(1_000_000)]
end
end
end
$ ruby bm3.rb
user system total real
array 0.670000 0.000000 0.670000 ( 0.690233)
hash 0.010000 0.000000 0.010000 ( 0.004873)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment