How to reduce Scala (/ Java) startup overhead?

前端 未结 3 1766
我寻月下人不归
我寻月下人不归 2020-12-14 08:15

I\'m pretty ignorant of the Java world (I do mostly C / Python) but Scala looked interesting enough to pull me in. One problem I\'m having with it is the enormous startup ov

3条回答
  •  爱一瞬间的悲伤
    2020-12-14 08:47

    You could work around the JVM start-up time by opening the Scala REPL and then loading your scripts directly into it using the :load command. This compiles (it does take some time, but I don't find it long in practice) the contents of the script and loads it for use in the REPL. For example:

    
    scala> :load testScript.scala
    Loading testScript.scala...
    import scala.collection.mutable.Map
    memory: scala.collection.mutable.Map[Int,Int] = Map()
    fib: (Int)Int
    res7: Int = 165580141
    
    scala> fib(10)
    res1: Int = 55
    
    scala> fib(11)
    res2: Int = 89
    
    scala> fib(12)
    res3: Int = 144
    
    scala> fib(13)
    res4: Int = 233
    

    For example, a typical workflow of mine when writing different prototypes in Scala is as follows. I have a text editor open in one window, and the Scala REPL in another. I write my code and then load it (:load script.scala). The results produced by the script are immediately available (as seen in the above transcript, res7) and any functions, classes or objects defined in the script are also available. And it's faster than running scala myScript.scala as the JVM is already loaded.

    If you go the compiled route, use fsc (the fast Scala compiler). The first time it's invoked it creates a daemon process that compiles the code. Therefore you will only have to pay the JVM start-up price once. Just note that if you change the value of CLASSPATH (the environment variable), you'll have to restart fsc (it's something that has bugged me for a while).

    -- Flaviu Cipcigan

提交回复
热议问题