From: Charles Hixson Date: 2012-08-19T15:53:39+09:00 Subject: Re: case vs if-else On 08/16/2012 09:03 AM, Regis d'Aubarede wrote: > Hello, > > test done with : > > a="x" > if a=="b" then 2 > elsif a=="c" then 1 > elsif a=="c" then 1 > .... 50 elsif > > a="x" > case a > when "g" then 1 > when "i" then 1 > when "j" then 1 > when "k" then 1 > when "l" then 1 > when "b" then 1 > .... 50 when > > 10 microsecondes with if, > 231 nanosecondes with case > > I use benchi, (from ruiby, see attachment), for this kind of test. > If you need performences, try mirah with a jvm ... > > Attachments: > http://www.ruby-forum.com/attachment/7683/benchi.png > > > Looks like you've found a "case" where case is better than if. Not too surprising, given that case *should* be optimized for multi-multi-way jumps, and if should handle the binary case better. I disagree with those who say that the timing considerations aren't important. They may not rule (if they did you wouldn't choose Ruby), but they will always be important. If you can notice the difference when looping 50 times, it would be rather significant when looping 50_000 times. That said, Ruby is a lot faster than it used to be. But you are right, I often wonder which approach would be the more efficient, and very high level languages tend to hide that from you. FWIW, I would prefer to be using a faster language, but I also prefer a language that's rapid to develop in. And "premature optimization" is a problem that is endemic to programmers that are concerned about execution speed. Quite often what you really need is a better algorithm. (But it sure is nice to be able to tell is some choice is going to really slow things down. I will often write special case pattern processors rather than using regular expressions because of this. It may not be true any longer, but at one point I timed one of my problems, and special case code in ruby was considerably more than 50 times faster than using a regular expression. That was years ago, and as I said it may not be true any longer. But I tend to presume that it's still true, and the only way to really be sure is to run exhaustive timing tests after every library or compiler change. -- Charles Hixson