What are the suggested alternatives for Class<T>.isAssignableFrom(Class<?> cls)?
Currently I am doing the profiling to a piece of code. During the profiling, I discovered that this very method call,
Class<T>.isAssignableFrom(Class<?> cls)
takes up to quite amount of the entire time.
Because this is a method from reflection, it takes a lot of time compared to normal keywords or method calls. I am wondering if there are some good alternatives for this method cal开发者_如何学编程ls?
"[I]t examines the Class type passed in through a method argument to see if the type matches certain qualifications."
To me, that implies that the method argument should be required to implement a particular interface or inherit from a particular class. Keep in mind, the interface could be a marker like RandomAccess. I realize changing your API may not be an option.
If you have an object whose class you are retrieving, you can replace this with:
obj instanceof ClassName
but I wouldn't say its faster. Actually, I doubt this causes any problems with the program execution. Don't overoptimize.
I don't know if this effects you, but I think it is worth noting that in the early days of Java 5, isAssignableFrom had significant performance problems that were later corrected. I couldn't find if the fix was backported to Java 5, but it certainly went into Java 6.
Additionally, the Sun JVM Performance Wiki points out that Class.isInstance and Class.isAssignableFrom are as performant as instanceof.
So if you are on Java 6 or later, there doesn't seem to be an alternative for Class.isAssignableFrom that will be faster than what is already there.
精彩评论