Skip to content

Instantly share code, notes, and snippets.

@schneems
Created October 13, 2018 19:56
Show Gist options
  • Save schneems/8412f1c85672c76fc9946111138d9e66 to your computer and use it in GitHub Desktop.
Save schneems/8412f1c85672c76fc9946111138d9e66 to your computer and use it in GitHub Desktop.
def early_return(val)
return val if val
"nope"
end
def compare_if(val)
if val
val
else
"nope"
end
end
def ternary(val)
val ? val : "nope"
end
require 'benchmark/ips'
Benchmark.ips do |x|
x.report("return") { early_return(true) }
x.report("if ") { compare_if(true) }
x.compare!
end
# Warming up --------------------------------------
# return 308.006k i/100ms
# if 308.924k i/100ms
# Calculating -------------------------------------
# return 9.983M (± 2.6%) i/s - 49.897M in 5.001941s
# if 9.991M (± 2.8%) i/s - 50.046M in 5.013219s
# Comparison:
# if : 9991239.4 i/s
# return: 9983041.6 i/s - same-ish: difference falls within error
Benchmark.ips do |x|
x.report("return") { early_return(true) }
x.report("ternary") { ternary(true) }
x.compare!
end
# Warming up --------------------------------------
# return 294.512k i/100ms
# ternary 283.869k i/100ms
# Calculating -------------------------------------
# return 9.250M (± 6.2%) i/s - 46.238M in 5.023791s
# ternary 9.705M (± 3.4%) i/s - 48.542M in 5.007776s
# Comparison:
# ternary: 9705281.6 i/s
# return: 9250189.8 i/s - same-ish: difference falls within error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment