Last active
December 12, 2017 19:28
-
-
Save agush22/7edc606cb15c3d142560755372dbf25f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 steps_each(arr_a, arr_b) | |
h_a = arr_a.to_h | |
h_b = arr_b.to_h | |
result = [] | |
h_a.keys.each do |k| | |
if h_b.member?(k) | |
result << [k, 'update', h_b[k]] if h_b[k] != h_a[k] | |
else | |
result << [k, 'delete'] | |
end | |
end | |
h_b.keys.each do |k| | |
result << [k, 'create', h_b[k]] unless h_a.member?(k) | |
end | |
result | |
end | |
def steps_diff(arr_a, arr_b) | |
h_a = arr_a.to_h | |
h_b = arr_b.to_h | |
result = [] | |
(h_a.keys - h_b.keys).each { |k| result << [k, 'delete'] } | |
(h_a.keys & h_b.keys).each { |k| result << [k, 'update', h_b[k]] if h_b[k] != h_a[k]} | |
(h_b.keys - h_a.keys).each { |k| result << [k, 'create', h_b[k]] } | |
result | |
end | |
a = [] | |
rand(100).times {a << [('a'..'z').to_a.sample, rand(50)]} | |
b = [] | |
rand(100).times {b << [('a'..'z').to_a.sample, rand(50)]} | |
puts steps_each(a,b).inspect | |
Benchmark.bm(10) do |x| | |
x.report('each:') { steps_each(a, b) } | |
x.report('diff:') { steps_diff(a, b) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment