c# - More efficient way to determine if a string starts with a token from a set of tokens? -


I am currently doing something that I am currently working on in some code:

  Public command type GetCommandTypeFromCommandString (string command) {if (with Command Concepts accept it). Type the command. accept; And if (commands start. Status) commandtip Event; And if (Command. Consultants. Echo) commandtie back Echo; And if (Command Strengts. Warning) Return to CommandType Warning; // and so on CommandType.None; }  

I want to know that there is a more efficient way to do this in C #. This code needs to be executed several times, many times, and I'm not very happy with the time it takes to compare those stars. Any suggestions? :)

To use an optimized string compiler enum, you will only want to compare gradually Like this:

  If (command contents, please accept, string commerzion. Ordinal)) Come back to the commandtip. accept;  

If you do not specify a string comparison method, then the current culture will be used for comparison and it will slow things down.

I did something (really inexperienced) Benchmarking:

  var a = "foo bar foo"; Var b = "foo"; Int numbers = 1000000; Benchmark Time (() => A.Start (B, String Comparison. Ordinal), "Ordinal", Number Times); Benchmark Time (() => A. Start (B), "Cultural Sensitive", Number of Times);  

The following results have been produced:

 successive 35.6033 ms went into culture sensitive 1000000 times 175.585 9 ms 1000000 times went 1000000 times 
< P> You should order your comparison so that the most likely token (happiness path) is being compared before.

This modernization optimization is an easy way to improve your current implementation, but if the performance is really important (and I mean, really important), in order to implement some kind of state machine Should look.


Comments