Java: Comparable vs Comparator - 内存和性能

Java: Comparable vs Comparator - Memory & Performance

在我的一次采访中,有人问我

What is the performance difference between Comparable and Comparator?

我回答说不知道。面试官说,

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.

他说的对吗?

答案不正确。

添加已实现的接口或方法不会影响 class 的各个实例所需的内存。

首先,概念上讲不通。

实现的接口和方法是每个class信息。相同 class 的两个实例将始终实现完全相同的接口并具有完全相同的方法。因此,JVM 为每个对象存储该信息是没有意义的。

其次,您可以使用如下示例代码轻松验证:

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 ...");
    }
  }
}

运行 这与 -Xmx32m 使用 Java 11 将为我在每个 运行 上创建大约 200000 个对象(有轻微的变化,可能是由于 GC 细节)。

删除 Comparable 接口 and/or compareTo 方法不会显着改变该值。

您可以尝试添加其他字段或删除 l,这 更改数字。