I wonder if there is a difference in performance between
checking if a value is greater / smaller than another
for(int x = 0; x < y; x++); // for y > x
and
checking if a value is not equal to another
for(int x = 0; x != y; x++); // for y > x
and why?
In addition: What if I compare to zero, is there a further difference?
It would be nice if the answers also consider an assebled view on the code.
EDIT: As most of you pointed out the difference in performance of course is negligible but I'm interested in the difference on the cpu level. Which operation is more complex?
To me it's more a question to learn / understand the technique.
I removed the Java
tag, which I added accidentally because the question was meant generally not just based on Java, sorry.
You should still do what is clearer, safer and easier to understand. These micro-tuning discussions are usually a waste of your time because
Note: the machine generated can also change with processor or JVM, so looking this is not very helpful in most cases, even if you are very familiar with assembly code.
What is much, much more important is the maintainability of the software.
The performance is absolutely negligible. Here's some code to prove it:
public class OpporatorPerformance {
static long y = 300000000L;
public static void main(String[] args) {
System.out.println("Test One: " + testOne());
System.out.println("Test Two: " + testTwo());
System.out.println("Test One: " + testOne());
System.out.println("Test Two: " + testTwo());
System.out.println("Test One: " + testOne());
System.out.println("Test Two: " + testTwo());
System.out.println("Test One: " + testOne());
System.out.println("Test Two: " + testTwo());
}
public static long testOne() {
Date newDate = new Date();
int z = 0;
for(int x = 0; x < y; x++){ // for y > x
z = x;
}
return new Date().getTime() - newDate.getTime();
}
public static long testTwo() {
Date newDate = new Date();
int z = 0;
for(int x = 0; x != y; x++){ // for y > x
z = x;
}
return new Date().getTime() - newDate.getTime();
}
}
The results:
Test One: 342
Test Two: 332
Test One: 340
Test Two: 340
Test One: 415
Test Two: 325
Test One: 393
Test Two: 329
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With