我现在正在做一些我现在正在做的代码:
public CommandType GetCommandTypeFromCommandString(String command)
{
if(command.StartsWith(CommandConstants.Acknowledge))
return CommandType.Acknowledge;
else if (command.StartsWith(CommandConstants.Status))
return CommandType.Status;
else if (command.StartsWith(CommandConstants.Echo))
return CommandType.Echo;
else if (command.StartsWith(CommandConstants.Warning))
return CommandType.Warning;
// and so on
return CommandType.None;
}
Run Code Online (Sandbox Code Playgroud)
我想知道在C#中是否有更有效的方法.这段代码需要每秒执行很多次,而且我对完成所有这些字符串比较所花费的时间不太满意.有什么建议?:)
Mar*_*son 11
一种优化方法是使用StringComparison枚举来指定您只需要进行序数比较.像这样:
if(command.StartsWith(CommandConstants.Acknowledge, StringComparison.Ordinal))
return CommandType.Acknowledge;
Run Code Online (Sandbox Code Playgroud)
如果您没有指定字符串比较方法,那么当前文化将用于比较,这会减慢一些速度.
我做了一些(真的很天真)基准测试:
var a = "foo bar foo";
var b = "foo";
int numTimes = 1000000;
Benchmark.Time(() => a.StartsWith(b, StringComparison.Ordinal), "ordinal", numTimes);
Benchmark.Time(() => a.StartsWith(b), "culture sensitive", numTimes);
Run Code Online (Sandbox Code Playgroud)
其中产生了以下结果:
ordinal ran 1000000 times in 35.6033 ms culture sensitive ran 1000000 times in 175.5859 ms
您还应该对比较进行排序,以便首先比较最可能的标记(快乐路径).
Theese优化是一种简单的方法,可以使您当前的实现更好,但如果性能真的很关键(我的意思是非常关键),那么您应该考虑实现某种状态机.