Sid Sid - 1 year ago 96
C# Question

Efficent way to check if a number is in a given range

Consider the following scenario:

  • I have 2 constants MAX & MIN

  • I get a new number x

Now to check if x in the given rage I would do something like this:

if(x >= MIN && X <= MAX)
//Some logic

I wondering if there's a better way to go talking about efficiency. I do know that's a very simple task, but I am just curious to know if there's a better way

Answer Source

First of all this is a typical case of micro-optimization that almost never pays off.

Having said that, the only way to 'optimize' this is if you know in advance that one of the comparisons is highly likely to produce false. If there is one, then put that comparison first, to take advantage of boolean short-circuit evaluation.

if (x >= MIN && x <= MAX) { ... } // most efficient if x >= MIN is hardly ever true


if (x <= MAX && x >= MIN) { ... } // most efficient if x <= MAX is hardly ever true

And if neither comparison is predictable, then we have all wasted time...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download