1

is a <= b faster (or performs better) than a < b + 1?

If you guys need a language to answer my question then I will throw in javascript because I use it the most.

Taureon
  • 75
  • 1
  • 9
  • 1
    There are a number of online tools that can let you compare the performance of two pieces of code. For example: https://jsben.ch/ . Though if you're having performance issues, it's almost certainly not due to which comparison operators you're using. Look for larger performance issues instead, and don't worry about something like this. – Nicholas Tower May 24 '21 at 17:23
  • 1
    Does this answer your question? [Is < faster than <=?](https://stackoverflow.com/questions/12135518/is-faster-than) – zcoop98 May 24 '21 at 20:01
  • First and foremost, it's doing something **different** (unless `b` is guaranteed to be a sufficiently small integer). – Bergi May 24 '21 at 23:00

1 Answers1

1

TL;DR: a <= b is Faster...


First, lets remember that all code operations, in any programming language, get distilled down to their machine code equivalents at some point (whether at run-time or compile time) in order to actually be executed, since processors (eg. CPUs) only understand machine code, not C# or JavaScript or Go.

With that in mind, we can break down both expressions into something closer to their base parts:

  • a <= b is exactly one operation, it can't be broken down any further
  • a < b + 1 is more than one operation, which (without brushing up on computer architecture) roughly breaks down to:
    • Calculate b + 1
    • Store the answer to b + 1 in cache (let's call this c)
    • Read c from cache
    • Then compute a < c

Given this answer, which shows that < and <= are equal in terms of speed/ efficiency (because they're both "jump"-type instructions at the processor level) we can say that a <= b is categorically faster than a < b + 1, simply because the former is only a single operation, while latter is more than one.

Put another way, if the comparison operation takes x time, and the addition/ store/ read together takes y time, then we know for sure that x + y time is greater than x time, because we know that both x and y are non-zero (no operation takes zero time).

...But You Shouldn't Really Care


Never forget, premature optimization is the root of all evil. You should not care about this level of optimization, because it's almost guaranteed not to matter. CPUs are fast. Your time and labor is much better spent on more obviously intensive and time-consuming operations, and only then if it's something you notice to be slower than you want or need.


Here's an actual benchmark if you'd like: https://jsben.ch/KVrug. It returns inconsistent results over multiple runs, which helps illustrate why this doesn't really matter for practical use. Like always, there are fringe cases where optimization of this level could come into play, but on the whole, it just won't matter.

zcoop98
  • 2,590
  • 1
  • 18
  • 31