Skip to content

Instantly share code, notes, and snippets.

@denisdefreyne
Created October 16, 2022 07:34
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 denisdefreyne/ee7adb6ab75ad40838d910f23564daea to your computer and use it in GitHub Desktop.
Save denisdefreyne/ee7adb6ab75ad40838d910f23564daea to your computer and use it in GitHub Desktop.
Set #any? vs. not #empty?

Calling #any? on Set is much slower than calling #empty? and negating it! Take a look at these benchmarks.

Warming up --------------------------------------
               #any?   182.420k i/100ms
         not #empty?     2.432M i/100ms
Calculating -------------------------------------
               #any?      1.834M (± 1.3%) i/s -      9.303M in   5.073017s
         not #empty?     24.254M (± 0.3%) i/s -    121.597M in   5.013433s

Comparison:
         not #empty?: 24254424.3 i/s
               #any?:  1834197.2 i/s - 13.22x  (± 0.00) slower
require 'benchmark/ips'
require 'set'
set = Set.new
10.times { set << rand }
p set
Benchmark.ips do |x|
x.report("#any?") do |times|
i = 0
while i < times
set.any?
i += 1
end
end
x.report("not #empty?") do |times|
i = 0
while i < times
!set.empty?
i += 1
end
end
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment