What does Java's record equals() method actually do under the hood?

137 Views Asked by At

In my Java code, I have a simple record class just like so:

record SingleIndexProperties<A>(A property) implements IndexProperties {

    // Here go implementations of IndexProperties methods; not relevant to question.

}

When I run a JMH benchmark of code using this record, I notice something interesting in the CPU time flame graph that is generated at the end:

Flame graph showing what the equals() actually does.

This is just an excerpt from a much larger flame graph of the benchmarked code. The interesting thing here is that, for some reason, the default equals() method of the record seems to be doing some dynamic calls.

Naively, I'd expect that the method would do something like this:

public boolean equals(Object o) {
     if (o instanceof SingleIndexProperties other)  {
         return Objects.equals(property, other.property);
     }
     return false;
}

Clearly, that is not the case. What does it actually do instead, and why? I looked for the source code, but I couldn't find anything.

(I'm on OpenJDK Temurin-21.0.1+12. The Pair you see in the flame graph is what is put into the record, and is itself also a record, whose equals() exhibits the same default behavior. Then inside the Pair, there are Integers.)

0

There are 0 best solutions below