case vs if

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:

Match multiple values:

The benchmarks:

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