From: Hugh Sasse Staff Elec Eng Date: 2000-11-23T05:38:23+09:00 Subject: [ruby-talk:6531] Faster to roll you own case statement? When converting code to use symbols instead of strings I got a slowdown. I thought that was interesting so I thought "perhaps it was the case statement I added to preserve the interface". So I tested it. For this code: #!/usr/local/bin/ruby -w class StringOrSymbol def with_case(thing) case thing when String thing.downcase.intern when Symbol thing else raise TypeError "thing of wrong type" end end def with_if(thing) if thing.is_a? String thing.downcase.intern elsif thing.is_a? Symbol thing else raise TypeError "thing of wrong type" end end def with_if2(thing) if String === thing thing.downcase.intern elsif Symbol === thing thing else raise TypeError "thing of wrong type" end end end wotsit = StringOrSymbol.new() 10000.times { wotsit.with_case("Somethin") } 10000.times { wotsit.with_if("Somethin") } 10000.times { wotsit.with_if2("Somethin") } 10000.times { wotsit.with_case(:somethin) } 10000.times { wotsit.with_if(:somethin) } 10000.times { wotsit.with_if2(:somethin) } neelix hgs 276 %> I got these timings: ruby -rprofile is_a_vs_case.rb % cumulative self self total time seconds seconds calls ms/call ms/call name 21.47 14.24 14.24 20000 0.71 0.95 StringOrSymbol#with_case 21.12 28.25 14.01 6 2335.00 11055.00 Fixnum#times 17.74 40.02 11.77 20000 0.59 0.84 StringOrSymbol#with_if 17.23 51.45 11.43 20000 0.57 0.83 StringOrSymbol#with_if2 8.26 56.93 5.48 60000 0.09 0.09 Module#=== 5.26 60.42 3.49 30000 0.12 0.12 String#downcase 4.69 63.53 3.11 30000 0.10 0.10 String#intern 4.22 66.33 2.80 30000 0.09 0.09 Kernel.is_a? 0.00 66.33 0.00 1 0.00 0.00 Class#new 0.00 66.33 0.00 3 0.00 0.00 Module#method_added 0.00 66.33 0.00 1 0.00 0.00 Class#inherited 0.00 66.33 0.00 1 0.00 0.00 Object#initialize 0.00 66.33 0.00 1 0.00 66330.00 #toplevel neelix hgs 275 %> So it seems for small case statements it is faster to create them with if...elsif..else...end. Of course, the case statement is more readable. It's ruby 1.6.1 on a Sun Sparc Enterprise 250, Solaris 2.7 Hugh hgs@dmu.ac.uk