DEV Community

Dmitry Voronov for JetRockets

Posted on • Updated on • Originally published at

Use hash or case-statement in Ruby?

Often, when we need to get a value based on the other one, we're using a case-statement. Like this

def realizing_trade_type(realizable_trade_type)
  case realizable_trade_type
  when 'buy'
  when 'short'
  when 'buy_contract'
  when 'short_contract'
Enter fullscreen mode Exit fullscreen mode

But, if the conditions and the results are simple values, why don't we use hash for this? We can :)

  'buy'            => 'sell',
  'short'          => 'cover',
  'buy_contract'   => 'sell_contract',
  'short_contract' => 'cover_contract'
Enter fullscreen mode Exit fullscreen mode

Here is the benchmark of both options, executed 10_000_000 times. It shows that a hash is faster in times for such the kind of usage.

>> require 'benchmark'
>> do |x|'hash') { 10_000_000.times { REALIZING_TRADE_TYPES['buy'] } }'case-statement') { 10_000_000.times { realizing_trade_type 'buy' } }'empty') { 10_000_000.times {} }
                      user     system      total        real
hash              0.990423   0.003412   0.993835 (  1.057612)
case-statement    1.752263   0.004531   1.756794 (  1.762030)
empty             0.380810   0.000728   0.381538 (  0.382153)
Enter fullscreen mode Exit fullscreen mode

So, it's better to use a hash when you are just retrieving some values (like in the example above). If there is additional logic to execute, a case-statement is still a way to go.

Top comments (0)