Java: Comparable vs Comparator - Memory & Performance

Viewed 499

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?

1 Answers

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.

Related