RFR: 8371319: java.lang.reflect.Method#equals doesn't short-circuit with same instances
Rémi Forax
forax at openjdk.org
Mon Nov 10 18:33:35 UTC 2025
On Mon, 10 Nov 2025 17:59:02 GMT, Chen Liang <liach at openjdk.org> wrote:
> There is currently no shortcut for fast equals for Method or Constructor. While the comparison for declaring class, name (interned strings' identity), and return type are very efficient with identity comparison, the comparison for parameter type is not so much: We always have to iterate through every parameter.
>
> Luckily, even though we are burdened with the different method and constructor instance due to setAccessible, their parameter type arrays are shared most of the time; in particular, in the same root method/constructor hierarchy, all instances share the same method object. Thus, we can perform a `==` check on the incoming array to provide a fast path.
>
> Benchmark numbers before and after:
>
> Benchmark Mode Cnt Score Error Units
> ExecutableCompareBenchmark.distinctParams avgt 5 1.189 ± 0.024 ns/op
> ExecutableCompareBenchmark.equalMethods avgt 5 2.449 ± 0.033 ns/op
> ExecutableCompareBenchmark.sameMethodObject avgt 5 0.541 ± 0.027 ns/op
>
> Benchmark Mode Cnt Score Error Units
> ExecutableCompareBenchmark.distinctParams avgt 5 1.186 ± 0.042 ns/op
> ExecutableCompareBenchmark.equalMethods avgt 5 1.078 ± 0.049 ns/op
> ExecutableCompareBenchmark.sameMethodObject avgt 5 0.395 ± 0.018 ns/op
Hello Chen,
Beware !
You may have also to test with ZGC (during the relocation phase),
because == may not be as fast as a pointer check.
-------------
PR Comment: https://git.openjdk.org/jdk/pull/28221#issuecomment-3513311587
More information about the core-libs-dev
mailing list