Skip to content

Instantly share code, notes, and snippets.

@kainage
Created October 2, 2015 18:37
Show Gist options
  • Save kainage/c9527a76cc89f397ae95 to your computer and use it in GitHub Desktop.
Save kainage/c9527a76cc89f397ae95 to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'securerandom'
require 'ostruct'
cids = {}
class Object
def deep_copy
Marshal.load(Marshal.dump(self))
end
end
class OpenStruct
def [](field)
self.send field
end
def process_field_copy(field, cids)
copy = self[field].deep_copy
cids.inject({}) do |hash, (cid, count)|
copy[cid] = self[field].fetch(cid, 0) + count
end
self[field] = copy
self.save
end
def process_field_merge(field, cids)
processable_cids = cids.inject({}) do |hash, (cid, count)|
hash[cid] = self[field].fetch(cid, 0) + count
hash
end
self[field] = self[field].merge(processable_cids)
self.save
end
end
1_000_000.times do
cids[SecureRandom.hex] = 1
end
puts Benchmark.measure {
OpenStruct.new(satisfied_cids: {}).process_field_merge(:satisfied_cids, cids)
}
puts Benchmark.measure {
OpenStruct.new(satisfied_cids: {}).process_field_copy(:satisfied_cids, cids)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment