Created
November 9, 2022 16:21
-
-
Save apotonick/ef8b5c8195d6869170ee02f47bf59b67 to your computer and use it in GitHub Desktop.
Benchmarking merging keyword arguments
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
gem "benchmark-ips" | |
require 'benchmark/ips' | |
# This is all about merging {config} or not. | |
# Never merge. Fastest. | |
def container_fast(activity, bla: "default") | |
{ | |
activity: activity, | |
bla: bla, | |
} | |
end | |
# Always merge {config}. Around 1/4 slower than not merging. | |
def container(activity, bla: "default", **config) | |
{ | |
activity: activity, | |
bla: bla, | |
**config | |
} | |
end | |
# Only merge if config contains tuples. Very slow. | |
def container_with_if(activity, bla: "default", **config) | |
hsh = { | |
activity: activity, | |
bla: bla, | |
} | |
hsh.merge(config) if config.any? | |
end | |
Benchmark.ips do |x| | |
x.report("new container") { container(nil) } | |
x.report("new container with hsh") { container(nil, key: "something") } | |
x.report("new container with if") { container_with_if(nil, key: "something") } | |
x.report("old container") { container_fast(nil) } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment