Skip to content

Instantly share code, notes, and snippets.

@SamSaffron
Created August 29, 2013 04:01
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save SamSaffron/6374131 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
@maciejkowalski
Copy link

Benching 2 elements

Rehearsal -----------------------------------------------------
zip 2               0.010000   0.000000   0.010000 (  0.011916)
naive 2             0.010000   0.000000   0.010000 (  0.007004)
smart zip 2         0.010000   0.000000   0.010000 (  0.010305)
each_with_index 2   0.010000   0.000000   0.010000 (  0.010639)
lazy 2            array_hash.rb:42:in `lazy': private method `lazy' called for [0, 1, 2]:Array (NoMethodError)
    from array_hash.rb:77:in `block (4 levels) in <main>'
    from array_hash.rb:77:in `times'
    from array_hash.rb:77:in `block (3 levels) in <main>'
    from /home/maciej/.rvm/rubies/ruby-1.9.3-p429-railsexpress/lib/ruby/1.9.1/benchmark.rb:280:in `measure'
    from /home/maciej/.rvm/rubies/ruby-1.9.3-p429-railsexpress/lib/ruby/1.9.1/benchmark.rb:257:in `block in bmbm'
    from /home/maciej/.rvm/rubies/ruby-1.9.3-p429-railsexpress/lib/ruby/1.9.1/benchmark.rb:255:in `each'
    from /home/maciej/.rvm/rubies/ruby-1.9.3-p429-railsexpress/lib/ruby/1.9.1/benchmark.rb:255:in `inject'
    from /home/maciej/.rvm/rubies/ruby-1.9.3-p429-railsexpress/lib/ruby/1.9.1/benchmark.rb:255:in `bmbm'
    from array_hash.rb:60:in `block in <main>'
    from array_hash.rb:50:in `each'
    from array_hash.rb:50:in `<main>'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment