Python vs JavaScript

Python 是个比较成熟的语言,运行速度在几年前是快于 JavaScript 的。但这些年
JavaScript 的解释器发展很快,特别是 Google 的 V8 和 Mozilla 的 SpiderMonkey,
将 JavaScript 的运行速度提升了一大块,以致 JavaScript 的运行速度大有反超 Python
之势,但 Python 也不甘示弱,PyPy 项目经过几年的开发之后,最近也在频频发布版本,
将 JIT 带到 Python 之中,所以谁比谁牛,还很难说。这里做个简单的测试:

测试环境:
CPU: Intel(R) Pentium(R) CPU G620 @ 2.60GHz 双核
操作系统: Debian GNU/Linux 6.0 64 位
Google JS 引擎: 来自 Node.js v0.6.12 (命令:node)
Mozilla JS 引擎:来自 xulrunner-11.0 (命令:xpcshell)
Python: Debian 自带的 Python 2.6.6 (命令:python)
PyPy: pypy-1.8 (命令:pypy)

先测试简单的循环累加,测试代码:
testSum.js

var i, j, s;

for (i = 0; i < 100; i++) {
s = 0;
for (j = 0; j < 100000; j++)
s += j;
}

if ('function' == typeof(print))
print(i, s);
else
console.log(i, s);
testSum.py


i = 0
while i < 100:
s = 0
j = 0
while j < 100000:
s += j
j += 1
i += 1

print i, s
测试结果:
time node testSum.js : 0m0.052s
time xpcshell testSum.js : 0m1.808s
time python testSum.py : 0m2.199s
time pypy testSum.py : 0m0.188s

再测试 Dict 操作,测试代码:
testDict.js


var D = {};

var i, s, k;

for (i = 0; i < 100000; i++)
D['k' + i] = i;

for (i = 0; i < 100; i++) {
s = 0;
for (k in D)
s += D[k];
}

if ('function' == typeof(print))
print(i, s);
else
console.log(i, s);
testDict.py


D = {}

i = 0
while i < 100000:
D['k%d' % i] = i
i += 1

i = 0
while i < 100:
s = 0
for k in D:
s += D[k]
i += 1

print i, s
测试结果:
time node testDict.js : 0m3.645s
time xpcshell testDict.js : 0m2.894s
time python testDict.py : 0m2.954s
time pypy testDict.py : 0m1.044s

测试总结:
循环累加操作:node < pypy < xpcshell < python 最慢的是 Python
Dict 操作: pypy < xpcshell < python < node 最慢的是 Node.js (Google V8 引擎)

经过简单的测试,个人感觉 Node.js 在运算速度方面是最快的,但内置的数据结构不
够优化,在所有的实现中是最差的。个人感觉,Node.js 的作者如果将 JavaScript 引擎
由 Google V8 换为 Mozilla SpiderMonkey 的话,在综合性能测试中,或许会更佳!另外
,本人非常看好 PyPy,随着 PyPy 的不断成熟,在大规模的业务逻辑开发中,用 Python
写代码,将是一种享受,运行速度也无需担忧!
一家之言,欢迎讨论!
[url]http://javaeye.vipsinaapp.com/rblog_sina[/url]

你可能感兴趣的:(python)