Last active
June 17, 2022 01:11
-
-
Save texpert/2a1cd2610c984f9cda774cd2b6e30636 to your computer and use it in GitHub Desktop.
Each, each_with_object, inject, merge Array to Hash transforming comparison
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
Warming up -------------------------------------- | |
assign&return 21.225k i/100ms | |
each 23.473k i/100ms | |
merge 3.283k i/100ms | |
merge! 9.870k i/100ms | |
map with tuples 19.764k i/100ms | |
each_with_object 21.362k i/100ms | |
Calculating ------------------------------------- | |
assign&return 229.939k (± 5.2%) i/s - 2.314M in 10.087643s | |
each 256.244k (± 7.3%) i/s - 2.559M in 10.028367s | |
merge 33.238k (± 4.4%) i/s - 334.866k in 10.093927s | |
merge! 101.249k (± 5.1%) i/s - 1.017M in 10.065749s | |
map with tuples 211.932k (± 4.3%) i/s - 2.135M in 10.089963s | |
each_with_object 231.771k (± 6.1%) i/s - 2.328M in 10.081857s | |
Comparison: | |
each: 256244.3 i/s | |
each_with_object: 231771.0 i/s - same-ish: difference falls within error | |
assign&return: 229938.5 i/s - same-ish: difference falls within error | |
map with tuples: 211932.0 i/s - 1.21x slower | |
merge!: 101249.3 i/s - 2.53x slower | |
merge: 33238.1 i/s - 7.71x slower | |
Code: | |
----------------------------- | |
# frozen_string_literal: true | |
# Install the necessary gems: | |
# gem install benchmark-ips | |
# gem install kalibera | |
require 'benchmark/ips' | |
# Enable and start GC before each job run. Disable GC afterwards. | |
# | |
# Inspired by https://www.omniref.com/ruby/2.2.1/symbols/Benchmark/bm?#annotation=4095926&line=182 | |
class GCSuite | |
def warming(*) | |
run_gc | |
end | |
def running(*) | |
run_gc | |
end | |
def warmup_stats(*) | |
end | |
def add_report(*) | |
end | |
private | |
def run_gc | |
GC.enable | |
GC.start | |
GC.disable | |
end | |
end | |
suite = GCSuite.new | |
User = Struct.new(:id, :stuff) | |
a = Array.new(10) { |i| User.new(i, stuff: rand(1000)) } | |
Benchmark.ips do |x| | |
x.config(:time => 10, :warmup => 5, :stats => :bootstrap, :confidence => 95) | |
x.report('assign&return') do | |
a.inject({}) { |memo, i| memo[i.id] = i.stuff; memo } | |
end | |
x.report('each') do | |
memo = {} | |
a.each { |i| memo[i.id] = i.stuff } | |
memo | |
end | |
x.report('merge') do | |
a.inject({}) { |memo, i| memo.merge(i.id => i.stuff) } | |
end | |
x.report('merge!') do | |
a.inject({}) { |memo, i| memo.merge!(i.id => i.stuff) } | |
end | |
x.report('map with tuples') do | |
a.map { |i| [i.id, i.stuff] }.to_h | |
end | |
x.report('each_with_object') do | |
a.each_with_object({}) { |i, memo| memo[i.id] = i.stuff } | |
end | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment