diff --git a/src/java.base/share/classes/java/lang/reflect/Method.java b/src/java.base/share/classes/java/lang/reflect/Method.java index b6ccbaa829452..80e0209249c8b 100644 --- a/src/java.base/share/classes/java/lang/reflect/Method.java +++ b/src/java.base/share/classes/java/lang/reflect/Method.java @@ -95,6 +95,8 @@ public final class Method extends Executable { // If this branching structure would ever contain cycles, deadlocks can // occur in annotation code. private Method root; + // Hash code of this object + private int hash; // Generics infrastructure private String getGenericSignature() {return signature;} @@ -381,7 +383,13 @@ public boolean equals(Object obj) { * method's declaring class name and the method's name. */ public int hashCode() { - return getDeclaringClass().getName().hashCode() ^ getName().hashCode(); + int hc = hash; + + if (hc == 0) { + hc = hash = getDeclaringClass().getName().hashCode() ^ getName() + .hashCode(); + } + return hc; } /** diff --git a/test/micro/org/openjdk/bench/java/lang/reflect/MethodBenchmark.java b/test/micro/org/openjdk/bench/java/lang/reflect/MethodBenchmark.java index 96a218d440594..4e682cf4e92f1 100644 --- a/test/micro/org/openjdk/bench/java/lang/reflect/MethodBenchmark.java +++ b/test/micro/org/openjdk/bench/java/lang/reflect/MethodBenchmark.java @@ -36,8 +36,9 @@ import org.openjdk.jmh.annotations.Warmup; /** - * Benchmark measuring the speed of Method/Method.getExceptionTypes() and - * getParameterTypes(), in cases where the result array is length zero. + * Benchmark measuring the speed of Method/Method.getExceptionTypes(), + * getParameterTypes() in cases where the result array is length zero, + * and hashCode(). */ @BenchmarkMode(Mode.AverageTime) @State(Scope.Benchmark) @@ -50,6 +51,7 @@ public class MethodBenchmark { Method emptyParametersMethod; Method oneExceptionMethod; Method oneParameterMethod; + Method hashCodeMethod; public MethodBenchmark() { try { @@ -58,6 +60,8 @@ public MethodBenchmark() { emptyExceptionsMethod = emptyParametersMethod; oneExceptionMethod = oneParameterMethod; + + hashCodeMethod = String.class.getDeclaredMethod("toString"); } catch (Exception e) { throw new RuntimeException(e); } @@ -82,4 +86,9 @@ public Object[] getParameterTypes() throws Exception { public Object[] getParameterTypesEmpty() throws Exception { return emptyParametersMethod.getParameterTypes(); } + + @Benchmark + public int getMethodHashCode() { + return hashCodeMethod.hashCode(); + } }