我目前正在我正在处理的一些代码中做类似的事情:
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;
}
我想知道在 C# 中是否有更有效的方法来做到这一点。这段代码需要每秒执行很多很多次,我对执行所有这些字符串比较所需的时间不太满意。有什么建议么? :)
一种优化是使用 StringComparison 枚举来指定您只需要序数比较。像这样:
if(command.StartsWith(CommandConstants.Acknowledge, StringComparison.Ordinal))
return CommandType.Acknowledge;
如果您不指定字符串比较方法,则将使用当前区域性进行比较,这会稍微减慢速度。
我做了一些(非常非常天真的)基准测试:
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);
产生以下结果:
ordinal ran 1000000 times in 35.6033 ms
culture sensitive ran 1000000 times in 175.5859 ms
您还应该对比较进行排序,以便首先比较最可能的标记(快乐路径)。
这些优化是使当前实现性能更好的简单方法,但如果性能确实很关键(我的意思是真的很关键),那么您应该考虑实现某种状态机。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)