Edit 2: This answer is probably incorrect in most cases, below, when I say that all of the above is true, it is still true, but the bottom part is incorrect for most processor architectures, see comments. However, I will say that it is theoretically possible to have some kind of JVM for some OS / Architecture that do this, but the JVM is probably poorly implemented or it is a strange architecture. In addition, this is theoretically possible in the sense that most conceivable things are theoretically possible, so I would take the last portion with salt.
Firstly, I'm not sure about C ++, but I can talk about Java.
Here is the code
public class Example { public static boolean less(final int a, final int b) { return a < b; } public static boolean lessOrEqual(final int a, final int b) { return a <= b; } }
Running javap -c on it, I get bytecode
public class Example { public Example(); Code: 0: aload_0 1: invokespecial #8
You will notice that the only difference is if_icmpge (if comparing more / equal) compared to if_icmpgt (if comparing more).
Everything above is a fact, the rest is my best guess about how if_icmpge and if_icmpgt based on the college course I took in assembler. To get a better answer, you should look at how your JVMs handle this. I assume that C ++ also comes down to a similar operation.
Edit: documentation on if_i<cond> here
The way computers compare numbers, subtracts one from the other and checks whether this number is 0 or not, so when a < b , if it subtracts b from a and sees, if the result is less than 0, the sign of the value ( b - a < 0 ) Make a <= b , although he must take an additional step and subtract 1 ( b - a - 1 < 0 ).
Usually this is a very minor difference, but this is not some kind of code, this is confusion! O (n ^ 2) is the average number of times we make this particular comparison because it is in the inner majority of loops.
Yes, this may have something to do with branch prediction. I am not sure, I am not an expert in this, but I think that this can also play an insignificant role.