Saturday, December 24, 2016

加速 jvm 的 start up time

最近因為個人嗜好,研究了一下 clojure 語言。既然開始動手研究,自然而然,會想實驗,如果…用 clojure 來做 shell script 會如何。然後,就立刻發現了,clojure 在 shell 下啟動,哪怕是一個 hello world 程式,啟動時間就需要 2 秒以上。

time /opt/test.clj hello world real 0m2.684s user 0m2.239s sys 0m0.186s


哇,這真是太扯了,怎麼會慢到這種程度?於是我就開始研究幾個問題:
(1) JVM 是不是真的很慢?
(2) 有沒有辦法來改進這件事?

第一個問題的答案滿曲折的,因為網路上也是各家有各家的說法,而 benchmark 本身就是一個研究的題目,我也不打算做太多嚴謹的驗証,最後我的結論是:JVM 是夠快的 virtual machine ,效能並不比 native code 差太多,幾乎是可以忽略的程度, 它就只有啟動的時候比較慢而已。很多 scripting languages ,像 Ruby, Python 會考慮編譯成 JAVA bytecode ,就是為了效能考慮。

第二個答案,我試了兩個解法:
解法 1 -- jamVM ( 原理就是:把大的 openjdk 的 JVM 換成小的 jamVM )

Let’s update our clojure executable /usr/bin/clojure:
#!/bin/sh

exec java -jamvm -jar /opt/clojure.jar "$@"
Let’s try it out:
time /opt/test.clj
hello world

real  0m0.866s
user  0m0.764s
sys   0m0.076s

解法 2 -- Drip (原理:It keeps a fresh JVM spun up in reserve with the correct classpath and other JVM options so you can quickly connect and use it when needed, then throw it away. Drip hashes the JVM options and stores information about how to connect to the JVM in a directory with the hash value as its name. )