Skip to content

Instantly share code, notes, and snippets.

@brennovich
Last active August 29, 2015 14:22
Show Gist options
  • Save brennovich/9a64f485afc139a66680 to your computer and use it in GitHub Desktop.
Save brennovich/9a64f485afc139a66680 to your computer and use it in GitHub Desktop.
each_with_object_each vs tap+each vs tap+update
require 'benchmark/ips'
Benchmark.ips do |x|
x.report 'tap' do
{}.tap { |results| each { |bucket| bucket.ids_by_type.each{ |type,ids| (results[type]||=[]); results[type] += ids } } }
end
x.report 'each_with_object' do
flat_map(&:ids_by_type).each_with_object({}) do |results, ids_by_type|
results.each do |type, ids|
ids_by_type[type] ||= []
ids_by_type[type] += ids
end
end
end
x.report 'update' do
{}.tap do |result_ids|
flat_map(&:ids_by_type).each do |ids_by_type|
result_ids.merge!(ids_by_type) { |_, previous_ids, next_ids| previous_ids | next_ids }
end
end
end
x.compare!
end
Calculating -------------------------------------
tap 16.692k i/100ms
each_with_object 14.559k i/100ms
update 17.104k i/100ms
-------------------------------------------------
tap 457.661k (±13.0%) i/s - 2.253M
each_with_object 411.019k (±14.2%) i/s - 2.024M
update 522.843k (±14.3%) i/s - 2.566M
Comparison:
update: 522843.5 i/s
tap: 457660.5 i/s - 1.14x slower
each_with_object: 411018.8 i/s - 1.27x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment