DEV Community

Dmitry Voronov for JetRockets

Posted on • Edited on • Originally published at jetrockets.pro

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'
    'sell'
  when 'short'
    'cover'
  when 'buy_contract'
    'sell_contract'
  when 'short_contract'
    'cover_contract'
  end
end
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 :)

REALIZING_TRADE_TYPES = {
  'buy'            => 'sell',
  'short'          => 'cover',
  'buy_contract'   => 'sell_contract',
  'short_contract' => 'cover_contract'
}.freeze
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'
true
>> Benchmark.bm(15) do |x|
  x.report('hash') { 10_000_000.times { REALIZING_TRADE_TYPES['buy'] } }
  x.report('case-statement') { 10_000_000.times { realizing_trade_type 'buy' } }
  x.report('empty') { 10_000_000.times {} }
end
                      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)