简体   繁体   English

搜索小型数组或在c#中使用if语句的性能更高?

[英]Is more performant to search a small array or use an if statement in c#?

Suppose I'm writing a parser and I need to check if the current token returned by Scanner::NextToken (for example) is one of a small set of values (say 5-10 items; few less or few more). 假设我正在编写一个解析器,并且需要检查Scanner :: NextToken返回的当前令牌(例如)是否是一小部分值(例如5-10个项目;少一些或少一些)中的一个。

In this small open source project (https://github.com/gsscoder/exprengine), inside the Parser class I've declared various static arrays that I query with Array::Contains() (see Parser::Ensure() method). 在这个小型开源项目(https://github.com/gsscoder/exprengine)中,在Parser类中,我声明了各种静态数组,这些数组是我使用Array :: Contains()查询的(请参阅Parser :: Ensure()方法) )。

I'm guessing if I can gain in performance using the same technique used in the scanner for check tokens, that is an helper method that uses an if statement (like the following): 我正在猜测是否可以使用扫描器中用于检查令牌的相同技术来提高性能,这是一种使用if语句的辅助方法(如下所示):

private static bool IsLineTerminator(int c)
{
  return c == 0x0A || c == 0x0D || c == 0x2028 || c == 0x2029;
}

Or maybe that also in the Scanner, I should use technique used in the Parser? 也许在Scanner中也应该使用Parser中使用的技术?

Any opinion (well motivated) will be appreciated; 任何意见(积极进取)将不胜感激; just don't suggest to generate parser/scanner using tools like ANTLR - I want to keep an hand-written implementation. 只是不建议使用ANTLR之类的工具生成解析器/扫描器-我想保留一个手写的实现。

Regards, Giacomo 问候,贾科莫

Essentially that's exactly what Array.Contains is doing. 本质上,这正是Array.Contains所做的。 You'll have a slightly more involved call stack using Contains as it's not going to be inlined to that degree, but the basic idea of what's happening is the same. 您将使用Contains有一个稍微复杂的调用堆栈,因为它不会内联到那个程度,但是发生了什么的基本思想是相同的。 It's unlikely you'll see a dramatic performance difference, but by all means profile the two methods and see for yourself. 您不太可能会看到巨大的性能差异,但是一定要介绍这两种方法并亲自观察。 The best way of knowing which method is faster is just to try it, not to ask random strangers. 知道哪种方法更快的最好方法就是尝试一下,而不是问随机的陌生人。

Another option to consider for an actual algorithm change which would potentially be faster is to use a HashSet as opposed to an array. 考虑可能会更快的实际算法更改的另一种选择是使用HashSet而不是数组。 For only 4 values the speed difference is likely to be small, but a hash-based data structure is specifically designed for much faster searching. 对于只有4个值,速度差异可能很小,但是专门设计了基于散列的数据结构以加快搜索速度。 (It's at least worth testing that as well). (至少也值得测试)。 A switch statement will also be implemented as a hash-based solution, so you could consider using that as well. switch语句还将实现为基于哈希的解决方案,因此您也可以考虑使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM