Ruby empty? vs any?
Calculating -------------------------------------
empty !empty? 186.749k i/100ms
small !empty? 183.897k i/100ms
bigger !empty? 181.951k i/100ms
empty any? 175.703k i/100ms
small any? 176.518k i/100ms
bigger any? 178.262k i/100ms
-------------------------------------------------
empty !empty? 10.926M (±11.5%) i/s - 53.597M
small !empty? 11.155M (± 9.8%) i/s - 54.985M
bigger !empty? 11.023M (±10.1%) i/s - 54.403M
empty any? 10.572M (±10.0%) i/s - 52.184M
small any? 10.279M (±10.5%) i/s - 50.661M
bigger any? 10.289M (±10.0%) i/s - 50.626M
Comparison:
small !empty?: 11154853.6 i/s
bigger !empty?: 11022700.1 i/s - 1.01x slower
empty !empty?: 10926497.7 i/s - 1.02x slower
empty any?: 10572180.0 i/s - 1.06x slower
bigger any?: 10289221.6 i/s - 1.08x slower
small any?: 10279437.8 i/s - 1.09x slower
require 'benchmark/ips'
empty_array = []
small_array = [1] * 30
bigger_array = [1] * 300
Benchmark.ips do |x|
x.report('empty !empty?') { !empty_array.empty? }
x.report('small !empty?') { !small_array.empty? }
x.report('bigger !empty?') { !bigger_array.empty? }
x.report('empty any?') { empty_array.any? }
x.report('small any?') { small_array.any? }
x.report('bigger any?') { bigger_array.any? }
x.compare!
end