Skip to content

Instantly share code, notes, and snippets.

@Thomascountz
Created September 5, 2020 13:49
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 Thomascountz/2de2b91d25a087cc80eeaff097df22ec to your computer and use it in GitHub Desktop.
Save Thomascountz/2de2b91d25a087cc80eeaff097df22ec to your computer and use it in GitHub Desktop.
Benchmark using ARGS constant for default method arguments
require 'benchmark/ips'
Benchmark.ips do |benchmark|
benchmark.config(time: 5, warmup: 2)
benchmark.report("keyword-args") do
def foo(a: nil, b: nil, c: nil, d: nil, e: 1)
bar(a: a, b: b, c: c, d: d, e: e)
end
def bar(a: nil, b: nil, c: nil, d: nil, e: 1)
e
end
foo()
end
benchmark.report("opts-hash") do
def foo(args={e: 1})
bar(args)
end
def bar(args={e: 1})
args[:e]
end
foo()
end
ARGS = {e: 1}.freeze
benchmark.report("opts-hash-constant") do
def foo(args=ARGS)
bar(args)
end
def bar(args=ARGS)
args[:e]
end
foo()
end
benchmark.compare!
end
# Warming up --------------------------------------
# keyword-args 115.586k i/100ms
# opts-hash 112.823k i/100ms
# opts-hash-constant 121.602k i/100ms
# Calculating -------------------------------------
# keyword-args 1.150M (± 1.3%) i/s - 5.779M in 5.025485s
# opts-hash 1.117M (± 2.2%) i/s - 5.641M in 5.054257s
# opts-hash-constant 1.204M (± 1.6%) i/s - 6.080M in 5.050975s
#
# Comparison:
# opts-hash-constant: 1204049.0 i/s
# keyword-args: 1150182.8 i/s - 1.05x (± 0.00) slower
# opts-hash: 1116677.8 i/s - 1.08x (± 0.00) slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment