For a simple class definition:
class Example {
def r() = Random.nextLong() + Random.nextLong() //I'm using scala utility class to be succinct
}
There are 2 ways to call r()
when both class "Example" and function name "fn" are dynamic, but already known at compilation (which minimize the overhead of calling "fn" repeatedly): Java Reflection & Scala reflection.
The Java Reflection has a much more simple API: you just use Class.getMethodWithParameterType to get a reflection method and it can be immediately applied to any instance of Example
class.
Scala reflection is more complex: For every instance of Example
class you need to acquire an instance mirror first, then use it to invoke the method.
The thing that surprises me is that Even with such complexity, Scala Reflection seems to be faster (see answers of Scala TypeTags and performance and Faster alternatives to Java's reflection for a comparison). Can anyone confirm my speculation? What's the cause of this gap?
Thanks a lot for any insight.