Home > Blockchain >  Which is better in C#? if (A bunch of or statements) v.s. if (list.contains)
Which is better in C#? if (A bunch of or statements) v.s. if (list.contains)

Time:12-31

How much slower would it be to make a list and check if it contains a value over doing multiple or statements?

List<char> validvalues = new List<char>
{
    'a', 'b', 'c', 'd'
};
if (validvalues.Contains(value))
{
    //do thing
}

versus

if (value == 'a' || value == 'b' || value == 'c' || value == 'd')
{
    //do thing
}

Is there an even better way to achieve this that I'm missing?

Edit: First of all I apologize for my stupid question. To clarify this is a drastic oversimplification of my use case which involves checking it against 16 characters and then 32 chars, then 48 chars etc.. up to 256 chars. I was thinking I could append 16 characters at a time to the already existing list and use the same list to check multiple times. Obviously creating a list and checking over it would be slower ig I was really asking how much this would be an issue.

CodePudding user response:

Using a list would probably be marginally slower since it has to create a structure, iterate over its contents, etc. The or would be likely compiled directly to IL that compares against constant values. In exchange for that, though, you get more flexibility to change the list at runtime. But, you could get that with a Set, improving the lookup time significantly in exchange for a slightly more expensive setup time. So it would depend on how big the list is and how many comparisons you do.

That said, the only way to know for sure is to try it both ways and measure it. I suspect that the difference would be insignificant unless you performed these tasks millions of times.

In addition, it's highly unlikely that something as simple as this would be a meaningful bottleneck to any application overall. If the application has any kind of I/O, that is probably more likely to be a bottleneck that looking up a value in a relatively small set.

  • Related