Accepted answer

The JVM doesn't optimize static initializers (which is what this is) to the same level that it optimizes method calls. Unfortunately, when you do a lot of work there, that hurts performance--this is a perfect example of that. This is also one reason why the old Application trait was considered problematic, and why there is in Scala 2.9 a DelayedInit trait that gets a bit of compiler help to move stuff from the initializer into a method that's called later on.

(Edit: fixed "constructor" to "initializer". Rather lengthy typo!)


Code inside a top-level object block is translated to a static initializer on the object's class. The equivalent in Java would be

class Performance{
      //expensive calculation
    public static void main(String[] args){
      //use result of expensive calculation

The HotSpot JVM doesn't perform any optimizations on code encountered during static initializers, under the reasonable heuristic that such code will only be run once.

Related Query

More Query from same tag