【纪念五∙一二】Firefox的Javascript引擎进步很大啊 越来越快
/*************************************************************************************************************** Author: zklhp
* Email: zklhp@
* QQ: 493165744
* Last update: 2013.5.12
* Licensed under CC-BY-SA 3.0
***************************************************************************************************************/
先上代码 还是前几天写的那个阶乘求和的 移植到Javascript了
程序代码:
var BASE = 1000000000; var SIZE = 8*1024; var END = SIZE - 1; var N = 5000; function factorial(result, n) { var tmp = 0; var carry = 0; var upper = 0; var i = END; while (result[++upper] == 0); while (i >= upper) { tmp = result[i] * n + carry; if (tmp < BASE) { result[i] = tmp; carry = 0; } else { carry = tmp / BASE; result[i] = tmp % BASE; } i--; } if (carry != 0) { result[i] = carry; } return result; } function add(dst, src) { var upper_dst = 0; var upper_src = 0; var tmp = 0; var carry = 0; var i = 0; while (dst[++upper_dst] == 0); while (src[++upper_src] == 0); for (i = END; i >= upper_src; i--) { tmp = dst[i] + src[i] + carry; if (tmp < BASE) { dst[i] = tmp; carry = 0; } else { dst[i] = tmp - BASE; carry = 1; } } if (dst[i] + carry != 0) { dst[i] = 1; } return dst; } function print_num(a) { var i = 0; var tmp = 0; var str = ""; var str_tmp = ""; while (a[++i] == 0); while (i <= END) { tmp = Math.floor(a[i++]); str_tmp = tmp.toString(); if (str_tmp.length < 9) { for (var t = 0; t < 9 - str_tmp.length; t++) { str += "0"; } } str += str_tmp; } for (i = 0; i < 9; i++) { if (str.charAt(i) != "0") break; } str = str.substring(i); if (typeof(print) == "undefined") { alert(str); } else { print(str); } return ; } var sum = new Array(SIZE); var f = new Array(SIZE); var i = 0; for (i = 0; i < SIZE; i++) { sum[i] = 0; f[i] = 0; } f[END] = 1; sum[END] = 1; for (i = 2; i <= N; i++) { f = factorial(f, i); sum = add(sum, f); } print_num(sum);
就是直接根据C代码写的 输出部分改动比较大 其他的都没大改
当然 这个算法是以我这个64位环境为基础写的。。。
应该说 Javascript做计算不大合适 因为是弱类型 稍微不注意就变浮点了
在我的环境下测试结果如下
Language Time (ms) Relative time
C (gcc O3 optimization, 64-bit Linux) 230 1×
Javascript (js-shell, ≈firefox 17, 64-bit Linux) 7192 31.2×
Javascript (js-shell, ≈firefox 23, 64-bit Linux) 681 2.96×
Javascript (js-shell, ≈firefox 23, 32-bit Windows XP) 990 4.30×
C (gcc O3 optimization, 64-bit Linux) 230 1×
Javascript (js-shell, ≈firefox 17, 64-bit Linux) 7192 31.2×
Javascript (js-shell, ≈firefox 23, 64-bit Linux) 681 2.96×
Javascript (js-shell, ≈firefox 23, 32-bit Windows XP) 990 4.30×
能和本地代码用时在一个数量级上 Javascript的效率挺好的嘛