NodeJs 比 Clojure 快吗? [英] Is NodeJs faster than Clojure?

查看:22
本文介绍了NodeJs 比 Clojure 快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习 Clojure.我注意到的第一件事是没有循环.没关系,我可以复发.那么我们来看看这个函数(来自 Practical Clojure):

I just started learning Clojure. One of the first things I noticed is that there are no loops. That's OK, I can recur. So let's look at this function (from Practical Clojure):

(defn add-up
  "Adds up numbers from 1 to n"
  ([n] (add-up n 0 0))
  ([n i sum] 
    (if (< n i)
      sum
      (recur n (+ 1 i) (+ i sum)))))

为了在 Javascript 中实现相同的功能,我们使用如下循环:

To achieve the same function in Javascript, we use a loop like so:

function addup (n) {
  var sum = 0;
  for(var i = n; i > 0; i--) {
    sum += i;
  }
  return sum;
}

计时后,结果如下:

input size: 10,000,000
clojure: 818 ms
nodejs: 160 ms

input size: 55,000,000
clojure: 4051 ms
nodejs: 754 ms

input size: 100,000,000
clojure: 7390 ms
nodejs: 1351 ms

然后我开始尝试经典的 fib(在阅读了this):

I then proceeded to try the classic fib (after reading this):

在clojure中:

(defn fib
  "Fib"
  [n]
  (if (<= n 1) 1
      (+ (fib (- n 1)) (fib (- n 2)))))

在js中:

function fib (n) {
  if (n <= 1) return 1;
  return fib(n-1) + fib(n-2);
}

同样,性能也有很大差异.

Again, the performance has quite some difference.

fib of 39
clojure: 9092 ms
nodejs: 3484 ms

fib of 40
clojure: 14728 ms
nodejs: 5615 ms

fib of 41
clojure: 23611 ms
nodejs: 9079 ms

注意我在 clojure 中使用 (time (fib 40)) 所以它忽略了 JVM 的启动时间.它们在 MacBook Air(1.86 Ghz Intel Core 2 Duo)上运行.

Note I'm using (time (fib 40)) in clojure so it's ignoring the bootup time for JVM. These are ran on a MacBook Air (1.86 Ghz Intel Core 2 Duo).

那么是什么导致 Clojure 在这里运行缓慢?为什么人们会说Clojure 很快"?

So what's causing Clojure to be slow here? And why do people say that "Clojure is fast"?

提前致谢,请不要进行火焰战争.

Thanks in advance and Please, no flame wars.

推荐答案

(set! *unchecked-math* true)

(defn add-up ^long [^long n]
  (loop [n n i 0 sum 0]
    (if (< n i)
      sum
      (recur n (inc i) (+ i sum)))))

(defn fib ^long [^long n]
  (if (<= n 1) 1
      (+ (fib (dec n)) (fib (- n 2)))))

(comment
  ;; ~130ms
  (dotimes [_ 10]
    (time
     (add-up 1e8)))

  ;; ~1180ms
  (dotimes [_ 10]
    (time
     (fib 41)))
  )

所有数字来自 2.66ghz i7 Macbook Pro OS X 10.7 JDK 7 64 位

All numbers from 2.66ghz i7 Macbook Pro OS X 10.7 JDK 7 64bit

如您所见,Node.js 被打败了.这是 1.3.0 alpha,但如果您知道自己在做什么,您可以在 1.2.0 中实现相同的目标.

As you can see Node.js is trounced. This is with 1.3.0 alphas, but you can achieve the same thing in 1.2.0 if you know what you're doing.

在我的机器上 Node.js 0.4.8 for addup 1e8 是 ~990ms,对于 fib 41 ~7600ms.

On my machine Node.js 0.4.8 for addup 1e8 was ~990ms, for fib 41 ~7600ms.

            Node.js  | Clojure
                     |
 add-up       990ms  |   130ms
                     |
 fib(41)     7600ms  |  1180ms

这篇关于NodeJs 比 Clojure 快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆