Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: What is faster? Compare two object references or compare two primitives?

Tags:

java

So what is the logic to say the the default equals(Object obj)

public boolean equals(Object obj){
  this == obj; 
}

or:

int a = 1;
int b = 2;
a == b;

Could be another type with another value, I just don't find any documentation in what the cost of each one is.

Adding a reason for this:

I was reading this question and I was thinking, if there is an optimization for comparing for example a value inside the object (like an int) and compare them instead of the reference

like image 410
A Monad is a Monoid Avatar asked Feb 02 '26 00:02

A Monad is a Monoid


1 Answers

Wrote a little class (feel free to run in your editor of choice)..

public class HelloWorld {

    public static void main(String []args) {
        HelloWorld app = new HelloWorld();

        int n = 100000;

        long startTime = System.nanoTime();
        app.doEqualsNull(n);
        long endTime = System.nanoTime();
        System.out.println("doEqualsNull (ns): " + (endTime - startTime)) ; 

        startTime = System.nanoTime();
        app.doEqualsThis(n);
        endTime = System.nanoTime();
        System.out.println("doEqualsThis (ns): " + (endTime - startTime)) ;

        startTime = System.nanoTime();
        app.doEqualsSameInt(n);
        endTime = System.nanoTime();
        System.out.println("doEqualsSameInt (ns): " + (endTime - startTime)) ;

        startTime = System.nanoTime();
        app.doEqualsDifferentInt(n);
        endTime = System.nanoTime();
        System.out.println("doEqualsDifferentInt (ns): " + (endTime - startTime)) ;
    }

    public void doEqualsNull(int n) {
        for (int i = 0 ; i < n ; i++) {
            this.equals(null);
        }
    }

    public void doEqualsThis(int n) {
        for (int i = 0 ; i < n ; i++) {
            this.equals(this);
        }
    }

    public boolean equals(Object obj){
        return this == obj; 
    }

    public void doEqualsSameInt(int n) {
        for (int i = 0 ; i < n ; i++) {
            this.equalsInt(5);
        }
    }

    public void doEqualsDifferentInt(int n) {
        for (int i = 0 ; i < n ; i++) {
            this.equalsInt(50);
        }
    }

    public boolean equalsInt(int other){
        return 5 == other; 
    }
}

Output:

doEqualsNull (ns): 3660106
doEqualsThis (ns): 3237291
doEqualsSameInt (ns): 2887368
doEqualsDifferentInt (ns): 2992786

Integer equality seems to take slightly shorter time (it's really really small difference) -- but again, I am guessing some branch prediction did kick into my super scientific calculations. :)

like image 66
Debosmit Ray Avatar answered Feb 03 '26 12:02

Debosmit Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!