Maddy
Maddy

Reputation: 2224

Efficiency : UUID vs int comparison in Java

Excuse if this is a too simple question.

Consider the following class:

public class Asset {
   private int id;
   private UUID uuid;
}

If I'm to check the equality of a large number of Asset objects based on their Id, which is more efficient in terms of performance, id vs uuid?

Upvotes: 0

Views: 1066

Answers (1)

Shubham Chaurasia
Shubham Chaurasia

Reputation: 2622

Asymptotically both are constant time O(1) comparisons.

UUID maintains most significant 64 bits and least significant 64 bits and compares them. Here is the equals() method.

public boolean equals(Object obj) {
    if ((null == obj) || (obj.getClass() != UUID.class))
        return false;
    UUID id = (UUID)obj;
    return (mostSigBits == id.mostSigBits &&
            leastSigBits == id.leastSigBits);
}

And Integer equality is also constant time.

public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        return value == ((Integer)obj).intValue();
    }
    return false;
}

But it should be noted that UUID comparison includes comparison of 2 long type of fields.

EDIT: thanks Chai T. Rex for mentioning that question asks about int
So the equality of two int is again straightforward(==) and constant time.

Upvotes: 1

Related Questions