Created
November 8, 2013 15:12
-
-
Save codefromthecrypt/7372371 to your computer and use it in GitHub Desktop.
checks to see how expensive a one-time reflective call to getDeclaredMethods is..
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.caliper.Benchmark; | |
import com.google.common.base.Function; | |
import com.google.common.base.Supplier; | |
import java.io.Serializable; | |
import java.lang.reflect.Method; | |
/** tests the impact of checking an interface to see if it is functional. */ | |
public class IsFunctionalInterfaceBench { | |
@Benchmark int notFunctional(int reps) { | |
int hashCode = 0; | |
for (int i = 0; i < reps; ++i) { | |
hashCode |= isFunctionalInterface(Serializable.class) ? 0 : 1; | |
} | |
return hashCode; | |
} | |
@Benchmark int func0(int reps) { | |
int hashCode = 0; | |
for (int i = 0; i < reps; ++i) { | |
hashCode |= isFunctionalInterface(Supplier.class) ? 0 : 1; | |
} | |
return hashCode; | |
} | |
@Benchmark int func1OverloadsObjectEquals(int reps) { | |
int hashCode = 0; | |
for (int i = 0; i < reps; ++i) { | |
hashCode |= isFunctionalInterface(Function.class) ? 0 : 1; | |
} | |
return hashCode; | |
} | |
/** | |
* true if the interface is a functional interface, having exactly one | |
* abstract method. Note methods from {@link Object} are not abstract! | |
*/ | |
static boolean isFunctionalInterface(Class<?> declaring) { | |
boolean found = false; | |
for (Method method : declaring.getDeclaredMethods()) { | |
if (found) return false; | |
if (matchesSignatureOfObjectMethod(method)) continue; | |
found = true; | |
} | |
return found; | |
} | |
private static boolean matchesSignatureOfObjectMethod(Method method) { | |
if (method.getParameterTypes().length == 0) { | |
if ("hashCode".equals(method.getName()) || "toString".equals(method.getName())) return true; | |
} | |
if (method.getParameterTypes().length == 1 && "equals".equals(method.getName()) // | |
&& Object.class.equals(method.getParameterTypes()[0])) { | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment