Skip to content

Instantly share code, notes, and snippets.

@tomfakes
Created June 24, 2019 03:22
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 tomfakes/7dfb9cbd64d130aff54363146b3c50ad to your computer and use it in GitHub Desktop.
Save tomfakes/7dfb9cbd64d130aff54363146b3c50ad to your computer and use it in GitHub Desktop.
Benchmark for Compact vs Nil check
require "benchmark/ips"
Benchmark.ips do |x|
x.config(:time => 5, :warmup => 2)
# To reduce overhead, the number of iterations is passed in
# and the block must run the code the specific number of times.
# Used for when the workload is very small and any overhead
# introduces incorrectable errors.
x.report("add-if-not-nil") do |times|
i = 0
add_item = "bar/bas/sdfsdf/fdfdsaf/fdsfdsaf/dsfdsf"
while i < times
array = [ :key ]
array << add_item if add_item
i += 1
end
end
x.report("skip-if-nil") do |times|
i = 0
add_item = nil
while i < times
array = [ :key ]
array << add_item if add_item
i += 1
end
end
x.report("build-and-compact") do |times|
i = 0
add_item = "bar/bas/sdfsdf/fdfdsaf/fdsfdsaf/dsfdsf"
while i < times
array = [ :key, add_item ].compact
i += 1
end
end
x.report("build-and-compact-nil") do |times|
i = 0
add_item = nil
while i < times
array = [ :key, add_item ].compact
i += 1
end
end
x.compare!
end
Warming up --------------------------------------
add-if-not-nil 213.305k i/100ms
skip-if-nil 230.887k i/100ms
build-and-compact 206.259k i/100ms
build-and-compact-nil
213.858k i/100ms
Calculating -------------------------------------
add-if-not-nil 25.357M (± 2.4%) i/s - 126.703M in 4.999725s
skip-if-nil 34.338M (± 2.3%) i/s - 171.780M in 5.005449s
build-and-compact 16.808M (± 2.2%) i/s - 84.154M in 5.009277s
build-and-compact-nil
16.473M (± 2.1%) i/s - 82.335M in 5.000452s
Comparison:
skip-if-nil: 34337930.8 i/s
add-if-not-nil: 25357210.2 i/s - 1.35x slower
build-and-compact: 16808426.0 i/s - 2.04x slower
build-and-compact-nil: 16473080.8 i/s - 2.08x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment