4

During one of my interview, I was asked

What is the performance difference between Comparable and Comparator?

I replied that I don't know. The interviewer said,

If Comparable is implemented by a class Employee, when 5000 Employee objects are created and added in an ArrayList, there will be 5000 objects with compareTo methods in heap memory. So unless absolutely necessary, don't use Comparable. With Comparator, the above mentioned memory overhead is eliminated.

Was he correct in saying that?

gokul
  • 85
  • 11
  • 9
    That's ... wrong ... additional methods on a class don't mean that instances of that method require more memory. – Joachim Sauer Mar 11 '20 at 13:48
  • 1
    I concur with Joachim. The method is on the class, not individual objects. It's actually preferable to use the Comparable interface and keep Comparators for objects outside of your control or if you're doing a complicated comparison that's abnormal. – Ryan Mar 11 '20 at 14:08

1 Answers1

6

That answer is incorrect.

Adding implemented interfaces or methods does not influence the memory required for individual instances of a class.

First of all, conceptually it doesn't make sense.

Implemented interfaces and methods are per-class information. Two instances of the same class will always implement exactly the same interfaces and have the exact same methods. As such, it makes no sense for the JVM to store that information per-object.

Second, you can easily verify that with sample code like this:

public class MyClass implements Comparable<MyClass> {

  private final long l;

  MyClass(long l) {this.l = l;}

  @Override
  public int compareTo(MyClass o) {
    return 0;
  }

  public static void main(String[] args) {
    long l = 0;
    try {
      var list = new ArrayList<MyClass>();
      while (true) {
        list.add(new MyClass(l++));
      }
    } catch (OutOfMemoryError e) {
      System.out.println("Created " + l + " objects before things went south ...");
    }
  }
}

Running this with -Xmx32m using Java 11 will create about 200000 objects on each run for me (with slight variations, probably due to GC details).

Removing the Comparable interface and/or the compareTo method does not significantly change that value.

You can try adding additional fields or removing l, which will change the number.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
  • 1
    There is another point of view. Let’s assume, just for a moment, there was a special JVM requiring per-method memory in each instance. Then, `java.lang.Object` does already define 11 methods. Any real-life `Employee` class modeling some business logic surely adds another dozen or two. And the interviewer really wasted time discussing a single `compareTo` method… – Holger Mar 12 '20 at 17:52