I notice that a lot of people are writing tons of ifs instead of use the case operator.

The case operator is much more readable. It can do more work than the ifs. And it should be faster by definition. Unfortunately in ruby it is faster only in > 2.x

With case you compare objects and match multiple values.


Example of compare objects:

case "this is string"
when String
  "it is a string"
else
  "not a string object"
end

 => "it is a string"

Match multiple values:

case 2
when *[1, 2, 3]
 "hmm its 2"
else
 "nope, not found"
end

 => "hmm its 2"

The benchmarks:

guda: ~  ∴ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]
guda: ~  ∴ irb

require 'benchmark'
n = 2_900_000

Benchmark.bm do |x|

  x.report("with case") do
    n.times.each do
      case n
      when 1
        1==1
      when 2
        1==1
      when 3
        1==1
      end
    end
  end

  x.report("with if") do
    n.times.each do
      1==1 if n == 1
      1==1 if n == 2
      1==1 if n == 3
    end
  end

end
       user     system      total        real
with case 0.210000 0.000000 0.210000 ( 0.214774)
with if 0.250000 0.000000 0.250000 ( 0.245829)

In this example case is doing 1==1 which is not needed, but just to be “fair” test.

Here are more benchmarks for older rubies: http://midwire.github.io/blog/2011/08/26/ruby-performance-case-vs-if-elsif/

 

Nice tool to expirment with for the next benchmarking: https://github.com/appfolio/abprof