Skip to content

Instantly share code, notes, and snippets.

@apotonick
Created November 9, 2022 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apotonick/ef8b5c8195d6869170ee02f47bf59b67 to your computer and use it in GitHub Desktop.
Save apotonick/ef8b5c8195d6869170ee02f47bf59b67 to your computer and use it in GitHub Desktop.
Benchmarking merging keyword arguments
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