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.
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.
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 furthera < b + 1
is more than one operation, which (without brushing up on computer architecture) roughly breaks down to:
b + 1
b + 1
in cache (let's call this c
)c
from cachea < 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).
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.