确定更有效的方式,如果字符串从一组标记的记号开始
问题说明
目前,我正在做这样的事情在一些代码,我现在工作的:
I'm currently doing something like this in some code I'm working on right now:
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#。该代码需要执行很多很多次第二,我不是太满意,它需要做的所有这些字符串比较的时间。有什么建议么? :)
I'd like to know if there is a more efficient way of doing this in C#. This code needs to execute many, many times a second, and I'm not too happy with the time it takes to do all of those string comparisons. Any suggestions? :)
正确答案
一种优化是使用StringComparison枚举指定您只想序号比较。像这样的:
One optimization would be to use the StringComparison enum to specify that you only want ordinal comparison. Like this:
if(command.StartsWith(CommandConstants.Acknowledge, StringComparison.Ordinal))
return CommandType.Acknowledge;
如果您没有指定字符串比较方法,当前文化将用于比较和减缓。事情倒有几分
If you don't specify a string comparison method the current culture will be used for comparison and that slows things down a bit.
我做了一些(真的很幼稚)基准:
I did some (really really naive) benchmarking:
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);
这产生以下结果:
Which produced the following results:
ordinal ran 1000000 times in 35.6033 ms
culture sensitive ran 1000000 times in 175.5859 ms
您应该因此,最有可能的令牌被首次(幸福路)相比,也为了你的比较。
You should also order your comparisons so that the most likely tokens are being compared first (happy path).
Theese优化是使你的当前实现一个简单的方法表现得更好,但如果表现真的是至关重要的(我的意思是真正的关键),你应该寻找在执行某种状态机的。
Theese optimizations are a simple way of making your current implementation perform better but if performance really is critical (and I mean really critical) you should be looking towards implementing some sort of state machine.
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfhieg
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20