[PATCH] Flip operands of && in java.lang.reflect.Parameter.equals()

Сергей Цыпанов sergei.tsypanov at yandex.ru
Thu Dec 19 22:12:20 UTC 2019


Hello,

while looking into an issue related to reflection
I've found out that Parameter.equals() could be slightly
improved by switching operands of &&.

Consider the worst case when we have a method

public String doSmth(String str1, String str2) {  return str1 + str2;  }

and we compare its params:

Method method = getClass().getMethod("doSmth", String.class, String.class);
Parameter[] parameters = method.getParameters();
boolean sameParam = parameters[0].equals(parameters[1])


In this case we compare two Executables (which are equal) and only then
fail the comparison when checking indices.

I propose to employ fail-fast approach and first check indices as
primitives comparation is likely to be faster than invocation of Executable.equals().

Patch is below

diff --git a/src/java.base/share/classes/java/lang/reflect/Parameter.java b/src/java.base/share/classes/java/lang/reflect/Parameter.java
--- a/src/java.base/share/classes/java/lang/reflect/Parameter.java
+++ b/src/java.base/share/classes/java/lang/reflect/Parameter.java
@@ -78,8 +78,7 @@
     public boolean equals(Object obj) {
         if(obj instanceof Parameter) {
             Parameter other = (Parameter)obj;
-            return (other.executable.equals(executable) &&
-                    other.index == index);
+            return other.index == index && other.executable.equals(executable);
         }
         return false;
     }



More information about the core-libs-dev mailing list