Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maciejkowalski/6376374 to your computer and use it in GitHub Desktop.
Save maciejkowalski/6376374 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment