谁是速度之王(Python vs JavaScript)? | 您所在的位置:网站首页 › 提升python抢购速度 › 谁是速度之王(Python vs JavaScript)? |
2019独角兽企业重金招聘Python工程师标准>>> 先测试简单的循环累加,测试代码: 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.052stime xpcshell testSum.js : 0m1.808stime 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 继续测,测试 List 操作,测试代码: testList.js var L = []; var i, k; for (i = 0; i < 100000; i++) L.push('k' + i); for (i = 0; i < 100000; i++) { if (i & 1) { k = L.shift(); L.splice(i, 0, k); } else { k = L.splice(i, 1)[0]; L.push(k); } } if ('function' == typeof(print)) print(i, L.length); else console.log(i, L.length);testList.py L = [] i = 0 while i < 100000: L.append('k%d' % i) i += 1 i = 0 while i < 100000: if i & 1: k = L[0] del L[0] L.insert(i, k) else: k = L[i] del L[i] L.append(k) i += 1 print i, len(L)测试结果:time node testList.js : 0m5.277stime xpcshell testList.js : 3m10.457stime python testList.py : 0m6.710stime pypy testList.py : 0m41.702s测试总结:循环累加操作:node < pypy < xpcshell < python 0m0.052s 0m0.188s 0m1.808s 0m2.199sDict 操作: pypy < xpcshell < python < node 0m1.044s 0m2.894s 0m2.954s 0m3.645sList 操作: node < python < pypy < xpcshell 0m5.277s 0m6.710s 0m41.702s 3m10.457s 经过简单的测试表明: Node.js 做单纯的运算无疑是最快的,但 Node.js 的 Dict 操作性能太差,List 操作却又是表现最好的。 xpcshell 做单纯的运算慢于 Node.js,做 Dict 运算快于 Node.js,但做 List 操作却是慢的离谱,是最慢的。 python 做单纯的运算是最慢的,Dict 操作表现还不错,List 操作表现也不错,个人感觉只要不是做大量的计算,还是比较适合实现复杂的业务逻辑的。 PyPy 做单纯的计算表现不俗,做 Dict 操作性能最好,但是做 List 操作还不如传统的 Python,个人感觉 PyPy 很有前途,但在某些地方或许还不够成熟。可以考虑在某些环境代替标准的 Python,毕竟两者是非常兼容的,可以互相替换。 最后的总结: Node.js 在适合的环境会表现的很好,但不要过度使用。 Python 作为一门成熟的语言,不容忽视,在复杂的环境下,或许 Python 也是好的选择。 作为语言的使用者,我们可以多了解几门语言,了解各自的优缺点,在适合的地方,将适合的语言派上用场。 |
CopyRight 2018-2019 实验室设备网 版权所有 |