[Mono-devel-list] mcs code for switches on strings

Paolo Molaro lupus at ximian.com
Sun Mar 21 10:37:33 EST 2004


On 03/20/04 Marcus wrote:
> In one of my projects, I have a large number of cases where I make three-way 
> decisions based on a string comparison. I wrote a short test program with a 
> three-way decision using nested if-statements and a switch statement to see 
> which was more efficient. I did have to use a large number of iterations in a 
> loop to get reliable timing numbers, but once I did, I found that using this 
> if-statement in a loop took about 112 ms:
[...]
> whereas this switch took about 889 ms:

Currently IsInterned () is a little expensive, so for a small number of
cases it dominates the runtime. The current implementation could be
improved a little, or we could write a different one and see how it
performs. Note that on the MS runtime you'll get beasically the same
numbers (at least on .Net 1.0, dunno if they optimized it later).
There are a number of strategies to implement switch on strings:
1) ifs with String.Equals ()
2) ifs after IsInterned ()
3) binary search
4) hashtable + switch on number

1 is probably best for small number of cases. 3 should perform
well when you have a few tens of cases. 2 can probably be made to
perform well with a number of case like 10-30. 4 would be required
when you have a hundred or more cases. It's not easy to produce
accurate numbers because it depends on the actual data. Anyone
willing to write a few tests with best/worst/average scenarios
for each different implementation?
Note that 2 is probably going to be deprecated, because it requires the
jit to intern all the strings in a method before starting execution, so
in the future we want to avoid it anyway.

lupus

-- 
-----------------------------------------------------------------
lupus at debian.org                                     debian/rules
lupus at ximian.com                             Monkeys do it better



More information about the Mono-devel-list mailing list