Last active
May 19, 2021 01:26
-
-
Save goldeneggg/922b4acf5cb242afc614348e6c368f50 to your computer and use it in GitHub Desktop.
Compare performance `Hash#merge` and `Hash#merge!` for Ruby 2.6
This file contains 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/ips' | |
require 'benchmark/memory' | |
class Hoge | |
class << self | |
DEFAULT_TIME = 5 | |
DEFAULT_WARMUP = 2 | |
def ips(title:, | |
time: DEFAULT_TIME, | |
warmup: DEFAULT_WARMUP, | |
suite: nil, | |
&block) | |
Benchmark.ips do |x| | |
x.time = time | |
x.warmup = warmup | |
x.config(suite: suite) unless suite.nil? | |
x.report(title) { block.call } | |
end | |
end | |
def memory(title:, &block) | |
Benchmark.memory do |x| | |
x.report(title) { block.call } | |
end | |
end | |
def ips_compare(procs:, | |
time: DEFAULT_TIME, | |
warmup: DEFAULT_WARMUP, | |
suite: nil, | |
result_holder: nil, | |
result_saver: nil) | |
Benchmark.ips do |x| | |
x.time = time | |
x.warmup = warmup | |
x.config(suite: suite) unless suite.nil? | |
procs.each do |p| | |
x.report(p[:title]) { p[:proc].call } | |
end | |
x.hold!(result_holder) unless result_holder.nil? | |
x.save!(result_saver) unless result_saver.nil? | |
x.compare! | |
end | |
end | |
def memory_compare(procs:, result_holder: nil) | |
Benchmark.memory do |x| | |
procs.each do |p| | |
x.report(p[:title]) { p[:proc].call } | |
end | |
x.hold!(result_holder) unless result_holder.nil? | |
x.compare! | |
end | |
end | |
end | |
end | |
PROCS = [ | |
{ | |
title: 'merge', | |
proc: Proc.new do | |
h = { hoge: 'hogehoge' } | |
h.merge({ huga: 'hugahugahuga' }) | |
end | |
}, | |
{ | |
title: 'merge!', | |
proc: Proc.new do | |
h = { hoge: 'hogehoge' } | |
h.merge!({ huga: 'hugahugahuga' }) | |
end | |
}, | |
] | |
Hoge.ips_compare(procs: PROCS) | |
Hoge.memory_compare(procs: PROCS) | |
Author
goldeneggg
commented
May 19, 2021
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment