• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

确定更有效的方式,如果字符串从一组标记的记号开始

用户头像
it1352
帮助1

问题说明

目前,我正在做这样的事情在一些代码,我现在工作的:

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? :)

正确答案

#1

一种优化是使用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
系列文章
更多 icon
同类精品
更多 icon
继续加载