Skip to content

Instantly share code, notes, and snippets.

@koseki
Created November 22, 2012 14:19
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save koseki/4131393 to your computer and use it in GitHub Desktop.
Array#index benchmark (block vs value)
#! /usr/bin/env ruby
require 'benchmark'
values = []
arrays = []
hashes = []
1000.times do |i|
values << i
array = [i]
hash = { :id => i }
0.times do |j|
array << j * i
hash[:"v#{j}"] = j * i
end
arrays << array
hashes << hash
end
n = 10000
Benchmark.bm(15) do |x|
x.report('value value') do
n.times do
r = rand(1000)
values.index r
end
end
x.report('value block') do
n.times do
r = rand(1000)
values.index { |x| x == r }
end
end
x.report('array value') do
n.times do
r = rand(1000)
array = arrays[r]
arrays.index array
end
end
x.report('array block') do
n.times do
r = rand(1000)
array = arrays[r]
arrays.index { |x| x[0] == r }
end
end
x.report('hash value') do
n.times do
r = rand(1000)
hash = hashes[r]
hashes.index hash
end
end
x.report('hash block') do
n.times do
r = rand(1000)
hash = hashes[r]
hashes.index { |x| x[:id] == r }
end
end
end
$ ruby array_index_bench.rb
user system total real
value value 0.140000 0.000000 0.140000 ( 0.144671)
value block 0.250000 0.000000 0.250000 ( 0.246818)
array value 1.660000 0.000000 1.660000 ( 1.659921)
array block 0.290000 0.000000 0.290000 ( 0.295605)
hash value 1.870000 0.000000 1.870000 ( 1.866465)
hash block 0.370000 0.000000 0.370000 ( 0.373319)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment