确定更有效的方式,如果一个字符串从一组标记的记号开始? [英] More efficient way to determine if a string starts with a token from a set of tokens?

查看:130
本文介绍了确定更有效的方式,如果一个字符串从一组标记的记号开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于确定更有效的方式,如果一个字符串从一组标记的记号开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆