Created
November 22, 2012 14:19
Array#index benchmark (block vs value)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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