作者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