Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion src/java.base/share/classes/java/lang/reflect/Method.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;}
Expand Down Expand Up @@ -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;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -50,6 +51,7 @@ public class MethodBenchmark {
Method emptyParametersMethod;
Method oneExceptionMethod;
Method oneParameterMethod;
Method hashCodeMethod;

public MethodBenchmark() {
try {
Expand All @@ -58,6 +60,8 @@ public MethodBenchmark() {

emptyExceptionsMethod = emptyParametersMethod;
oneExceptionMethod = oneParameterMethod;

hashCodeMethod = String.class.getDeclaredMethod("toString");
} catch (Exception e) {
throw new RuntimeException(e);
}
Expand All @@ -82,4 +86,9 @@ public Object[] getParameterTypes() throws Exception {
public Object[] getParameterTypesEmpty() throws Exception {
return emptyParametersMethod.getParameterTypes();
}

@Benchmark
public int getMethodHashCode() {
return hashCodeMethod.hashCode();
}
}