Oftentimes there are multiple ways to achieve the same thing in Ruby. For example, one thing I've recently tried to make a habit of is to use #zero? when checking if a value is, well, zero. It definitely reads nicer than doing a value == 0 comparison, but is it also faster?

There's a really easy way how to find this out: use the benchmark module within the Ruby standard library. This allows you to check the runtime of two or even more statements against each other.

For our #zero? vs value == 0 case, we setup a test run like so:

require 'benchmark'

n = 500_000
Benchmark.bm do |x|
  x.report { n.times { 1 == 0 } }
  x.report { n.times { 1.zero? } }
end

We execute each statement 500.000 times, and this is what we get:

user     system      total        real
0.210000   0.000000   0.210000 (  0.213145)
0.250000   0.000000   0.250000 (  0.254806)

Turns out #zero? does read nicer, but it's roughly 20% slower than comparing with ==. Is it still worth using it? Definitely.