Just because I like such things, I compared solutions, just wanted to share it if someone is interested (I just switched the array to a larger one to get more meaningful results)
require "benchmark/ips"
def method_1(ar_1, ar_2)
ar = ar_1.zip ar_2
ar.count { |els| els[0] == els[1] }
end
def method_2(ar_1, ar_2)
count = 0
ar_1.each_with_index { |el, i| count += 1 if el == ar_2[i] }
end
def method_3(ar_1, ar_2)
count = 0
(0...ar_1.length).each do |idx|
count += 1 if ar_1[idx] == ar_2[idx]
end
end
def method_4(ar_1, ar_2)
ar_1.zip(ar_2).inject(0) do |memo, (left, right)|
if left == right
memo
else
memo + 1
end
end
end
def method_5(ar_1, ar_2)
ar_1.select.each_with_index do |item, index|
ar_2[index] != item
end
end
Benchmark.ips do |x|
ar_1 = (0..1_000_000).to_a.shuffle
ar_2 = (0..1_000_000).to_a.shuffle
x.report("zip and count") do |times|
i = 0
while i < times
method_1 ar_1, ar_2
i += 1
end
end
x.report("each with index") do |times|
i = 0
while i < times
method_2 ar_1, ar_2
i += 1
end
end
x.report("0..length each") do |times|
i = 0
while i < times
method_3 ar_1, ar_2
i += 1
end
end
x.report("zip and inject") do |times|
i = 0
while i < times
method_4 ar_1, ar_2
i += 1
end
end
x.report("select each with index") do |times|
i = 0
while i < times
method_5 ar_1, ar_2
i += 1
end
end
x.compare!
end
source
share