Created
September 5, 2020 13:26
-
-
Save Thomascountz/33428b5966edcf44e3e45794d258550b to your computer and use it in GitHub Desktop.
Benchmark using ARGS constant for method arguments
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' | |
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: nil) | |
bar(a: a, b: b, c: c, d: d, e: e) | |
end | |
def bar(a: nil, b: nil, c: nil, d: nil, e: nil) | |
e | |
end | |
foo(e: 1) | |
end | |
benchmark.report("opts-hash") do | |
def foo(args={}) | |
bar(args) | |
end | |
def bar(args={}) | |
args[:e] | |
end | |
foo(e: 1) | |
end | |
ARGS = {}.freeze | |
benchmark.report("opts-hash-constant") do | |
def foo(args=ARGS) | |
bar(args) | |
end | |
def bar(args=ARGS) | |
args[:e] | |
end | |
foo(e: 1) | |
end | |
benchmark.report("opts-splat") do | |
def foo(**args) | |
bar(args) | |
end | |
def bar(args) | |
args[:e] | |
end | |
foo(e: 1) | |
end | |
benchmark.report("caller-splat") do | |
def foo(**args) | |
bar(**args) | |
end | |
def bar(**args) | |
args[:e] | |
end | |
foo(**{e: 1}) | |
end | |
benchmark.compare! | |
end | |
### RESULTS ### | |
# Warming up -------------------------------------- | |
# keyword-args 109.985k i/100ms | |
# opts-hash 108.705k i/100ms | |
# opts-hash-constant 109.232k i/100ms | |
# opts-splat 99.706k i/100ms | |
# caller-splat 68.788k i/100ms | |
# Calculating ------------------------------------- | |
# keyword-args 1.040M (± 1.0%) i/s - 5.279M in 5.077242s | |
# opts-hash 1.028M (± 2.0%) i/s - 5.218M in 5.077435s | |
# opts-hash-constant 982.599k (± 8.4%) i/s - 4.915M in 5.043748s | |
# opts-splat 934.116k (± 1.3%) i/s - 4.686M in 5.017618s | |
# caller-splat 681.345k (± 1.1%) i/s - 3.439M in 5.048571s | |
# | |
# Comparison: | |
# keyword-args: 1039889.1 i/s | |
# opts-hash: 1028102.1 i/s - same-ish: difference falls within error | |
# opts-hash-constant: 982598.6 i/s - same-ish: difference falls within error | |
# opts-splat: 934116.0 i/s - 1.11x (± 0.00) slower | |
# caller-splat: 681344.8 i/s - 1.53x (± 0.00) slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment