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
require 'benchmark' | |
def zip_it(array1,array2) | |
Hash[array1.zip(array2)] | |
end | |
def naive(array1,array2) | |
hash = {} | |
index = 0 | |
length = array1.length | |
while index < length | |
hash[array1[index]] = array2[index] | |
index+=1 | |
end | |
hash | |
end | |
def smart_zip(array1,array2) | |
hash = Hash.new | |
array1.zip(array2) do |x,y| | |
hash[x] = y | |
end | |
hash | |
end | |
def each_with_index(array1,array2) | |
hash = Hash.new | |
array1.each_with_index do |elem, idx| | |
hash[elem] = array2[idx] | |
end | |
hash | |
end | |
def lazy(array1,array2) | |
hash = Hash.new | |
array1.each_with_object(array2.lazy) do |elem, elem2| | |
hash[elem] = elem2.next | |
end | |
hash | |
end | |
[2,20,40,60,100].each do |i| | |
array1 = (0..i).to_a | |
array2 = (0..i).to_a | |
puts | |
puts "Benching #{i} elements" | |
puts | |
Benchmark.bmbm do |x| | |
x.report("zip #{i}") do | |
10000.times{zip_it(array1,array2)} | |
end | |
x.report("naive #{i}") do | |
10000.times{naive(array1,array2)} | |
end | |
x.report("smart zip #{i}") do | |
10000.times{smart_zip(array1,array2)} | |
end | |
x.report("each_with_index #{i}") do | |
10000.times{each_with_index(array1,array2)} | |
end | |
x.report("lazy #{i}") do | |
10000.times{lazy(array1,array2)} | |
end | |
end | |
end |
maciejkowalski
commented
Aug 29, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment