作者Schelfaniel (Schelfaniel)
看板PLT
標題[閒聊] JVM 語言的速度(包含 clojure reverse number 改寫)
時間Thu Jul 30 11:37:59 2009
原網頁
http://www.slideshare.net/michael.galpin/performance-comparisons-of-dynamic-languages-on-the-java-virtual-machine?type=powerpoint
該作者很明顯除了 Java 之外的語言,都沒有以速度為第一考量來寫 :QQ
這邊我先改寫一下其中最後一個範例 reverse number 的 clojure 版如下:
; 原始版
(defn all-odd? [n]
(every? odd? (map #(Integer. (str %)) (str n))))
; 修改版,改用 Character
(defn all-odd2? [n]
(every? odd? (map #(Character/digit (char %) 10) (str n))))
; 修改版,減少迴圈數
(defn all-odd3? [n]
(every? #(odd? (Character/digit #^Character % 10)) (str n)))
; 修改版,加入 Type Hint
(defn all-odd4? [n]
(every? (fn [#^Character x] (odd? (Character/digit x 10))) (str n)))
時間比較
user=> (time (dotimes [_ 1000000] (all-odd? "13579")))
"Elapsed time: 6477.573178 msecs"
nil
user=> (time (dotimes [_ 1000000] (all-odd2? "13579")))
"Elapsed time: 5757.743914 msecs"
nil
user=> (time (dotimes [_ 1000000] (all-odd3? "13579")))
"Elapsed time: 2817.708957 msecs"
nil
user=> (time (dotimes [_ 1000000] (all-odd4? "13579")))
"Elapsed time: 1905.122916 msecs"
nil
; 原始版
(defn reverse-num [n]
(+ n (Integer. (apply str (reverse (str n))))))
; 修改版,加入 Type Hint
(defn reverse-num2 [n]
(+ n (Integer. #^String (apply str (reverse (str n))))))
時間比較
user=> (time (dotimes [_ 1000000] (reverse-num 12345)))
"Elapsed time: 15353.399251 msecs"
nil
user=> (time (dotimes [_ 1000000] (reverse-num2 12345)))
"Elapsed time: 4573.696402 msecs"
nil
; 原始版
(defn reversible-num? [n]
(all-odd? (reverse-num n)))
; 修改版
(defn reversible-num2? [n]
(all-odd4? (reverse-num2 n)))
; 原始版
(defn count-reversible [rev-max]
{:max rev-max :num-reversible (count (filter reversible-num? (range 11
rev-max)))})
; 修改版
(defn count-reversible2 [rev-max]
{:max rev-max :num-reversible (count (filter reversible-num2? (range 11
rev-max)))})
整體測試,時間壓到一半以下
user=> (time (count-reversible 1000000))
"Elapsed time: 23196.033344 msecs"
{:max 1000000, :num-reversible 23374}
user=> (time (count-reversible2 1000000))
"Elapsed time: 10627.854116 msecs"
{:max 1000000, :num-reversible 23374}
其實 reverse-num 那邊,改用 Java Array 應該還可以更快 :QQ
不過目前沒時間寫了
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 163.29.28.137
※ 編輯: Schelfaniel 來自: 163.29.28.137 (07/30 11:54)
1F:→ sbrhsieh:或許你會對 JSR 292 感興趣,留意一下其進度。 08/01 01:01