0
votes

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.

1
Unless you need to call the method billions of times, this is premature optimization. Don't worry about it until you can determine it's actually a problem via profiling. It will likely never matter.Jim Garrison
I know, I'm implementing both as backups, but still I would like to know if my profiling result will coincide with other's observationstribbloid

1 Answers

1
votes

For method invocation, Scala reflection uses Java reflection, so it can hardly be faster.

Scala Reflection seems to be faster (see answers of Scala TypeTags and performance and Faster alternatives to Java's reflection for a comparison)

If you just compare the numbers, Scala reflection seems much, much slower: Java takes ~0.4 seconds for 50 million iterations, Scala takes ~0.01 seconds for 100 iterations.

But of course you can't compare these numbers at all: they are done on different computers, with different setups, different JVM versions, different warmup, Scala is looking up the method every time where Java gets it once and invokes many times, the methods measured are different, etc. etc. etc.