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

查看:108
本文介绍了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):

in clojure:

in clojure:

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



in 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 alphas,但你可以在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对于加法1e8是〜990ms,对于纤维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天全站免登陆