Ruby Benchmarking CASE WHEN x HASH


Today I found a resuld I did never expected, it goes like this…

Intro: I thought: in a hash there must have a hash function that is somehow costly  to map a key to a value, right? And while learning C in my grad, I were taught that SWITCH CASE was a very fast and optimized structure.

So.. If i get the ruby’s equivalent CASE WHEN to map a key to a value dynamically that should be really fast! Dead Wrong!

I benchmarked 3 ways: A fixed CASE WHEN, a evalued CASE WHEN, and the friendly HASH, and got these results:

@ ruby 1.8.7 (2009-06-12 patchlevel 174) [i486-linux]

      user     system      total        real
CASE WHEN         1.370000   0.130000   1.500000 (  1.507988)
EVAL CASE WHEN  15.110000   0.440000  15.550000 ( 15.548754)
HASH[:sym]       1.000000   0.140000   1.140000 (  1.147406)

@ ruby 1.9.1p243 (2009-07-16 revision 24175) [i486-linux]

      user     system      total        real
CASE WHEN         0.710000   0.000000   0.710000 (  0.707460)
EVAL CASE WHEN  34.460000   0.010000  34.470000 ( 34.460126)
HASH[:sym]       0.410000   0.000000   0.410000 (  0.416476)

The source is here:

require	'benchmark' do|b|
 vdd = {:a =>	'amor',
 :b	=> 'valor',
 :c	=> 'honestidade',
 :d	=> 'tabela',
 :e	=> 'sinceriadade'
 }'CASE WHEN       ') do
	1_100_000.times {
		valor_unico = [:a,:b,:c,:d,:e][rand(4)]
		case valor_unico;	when :a then	'amor';	when :b then	'valor';	when :c then	'honestidade';	when :d then	'tabela';	when :e then	'sinceriadade';	else	false; end;
end"EVAL CASE WHEN ") do
	$tree = 'case valor_unico;	'
	vdd.each	{	|k,v|	$tree	<< "when :#{k} then	'#{v}';	"	}
	$tree <<	'else	false; end;'
	def case_when(v)
		valor_unico	=	v
		eval $tree

	1_100_000.times { case_when(	[:a,:b,:c,:d,:e][rand(4)]	)	}
 end"HASH[:sym]     ") do
	1_100_000.times { vdd[	 [:a,:b,:c,:d,:e][rand(4)]	]	}

And the Conclusion is: Using a Hash can be pretty fast, since it must be really optimized structure in Ruby!
The CASE WHEN felt slow compared to the hash, as weird as may be :P.
Hashes still have the advantage of very simple reading, writing and updating for the programmer, they also append values easily.

Improving: A potencial future test would be to make a hash that is way bigger than this, the results could change a little.
Other idea is mapping the key for something other than a Symbol, like a String or a custom Object.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s