简体   繁体   中英

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).

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).

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

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?

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.

Regards, Giacomo

Essentially that's exactly what Array.Contains is doing. 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. 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. 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. (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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