The Spaghetti Refactory Established 2015

present? vs any? in Rails

First, a few definitions, direct from the Ruby docs  and Rails docs:

present?
An object is present if it’s not blank?

blank?
An object is blank if it’s false, empty, or a whitespace string.

any?
Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil. If the block is not given, Ruby adds an implicit block of { |obj| obj } that will cause any? to return true if at least one of the collection members is not false or nil. 

present? is a Rails method from ActiveSupport
any? is pure Ruby A few important points:

nil.any?
# => NoMethodError: undefined method `any?' for nil:NilClass

nil.present?
# => false

[""].any? && [""].present?
# => true

[""].any? &:present?
# => false

The last example is good if you need to make sure there are no blank values in an array.

 So, how do all of these measure up, performance-wise? Well, they're all pretty similar, but it seems that any? is moderately faster than present, so if you can get away with it, go for that one. However, as far as I'm concerned, when dealing with such a small performance difference, readability becomes more important, so I would personally go for whichever is more readable that still accomplishes my purposes. With arrays, that tends to be any? most of the time.

Benchmarks:

array = (0..500000).to_a
Benchmark.bmbm do |x|
x.report("any with empty array:") { 100000.times { [].any? } }
x.report("present with empty array:") { 100000.times { [].present? } }
x.report("any with stuff:") { 100000.times { array.any? } }
x.report("present with stuff:") { 100000.times { array.present? } }
end

user system total real
any with empty array: 0.010000 0.000000 0.010000 ( 0.010986)
present with empty array: 0.010000 0.000000 0.010000 ( 0.015146)
any with stuff: 0.010000 0.000000 0.010000 ( 0.008500)
present with stuff: 0.010000 0.000000 0.010000 ( 0.012448)

Tags