Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance: greater / smaller than vs not equal to

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.

like image 823
das Keks Avatar asked Sep 03 '13 15:09

das Keks


2 Answers

You should still do what is clearer, safer and easier to understand. These micro-tuning discussions are usually a waste of your time because

  • they rarely make a measurable difference
  • when they make a difference this can change if you use a different JVM, or processor. i.e. without warning.

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.

like image 137
Peter Lawrey Avatar answered Nov 10 '22 12:11

Peter Lawrey


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
like image 16
James Dunn Avatar answered Nov 10 '22 12:11

James Dunn