第4页
- 页码:第4页 2011-06-08 09:32:49
程序P2和P3:直接上代码!
function root(n) { return Math.sqrt(n); } function prime(n) { var i, bound; bound = root(n); for(i = 2; i <= bound; ++i) { if (n % i == 0) { return 0; } } return 1; } function main() { var i, n, html = ''; n = 1000; for (i = 2; i < n; ++i) { if (prime(i)) { html += i + ' , '; } } document.writeln(html); } main();偶然发现:在《高性能JS》书中将 profiler 这个术语译为:性能分析工具,而这本书则译为:性能监视工具了。 由于JS程序的 profiler 工具都不能对函数内部走了多少次数进行统计,所以,只好自己编写统计次数的了:
var count = 0, count0 = 0,count1 = 0; function root(n) { count = count + 1; return Math.sqrt(n); } function prime(n) { var i, bound; bound = root(n); count0 = count0 + 1; for(i = 2; i <= bound; ++i) { count1 = count1 + 1; if (n % i == 0) { return 0; } } return 1; } function main() { var i, n, html = ''; n = 1000; for (i = 2; i < n; ++i) { if (prime(i)) { html += i + ' , '; } } document.writeln(html); console.log(count, count0, count1); } main();最后的程序P5:
var count = 0, count0 = 0, count1 = 0; function root(n) { count = count + 1; return Math.sqrt(n); } function prime(n) { var i, bound; if (n % 2 == 0) { return (n == 2); } if (n % 3 == 0) { return (n == 3); } if (n % 5 == 0) { return (n == 5); } bound = root(n); count0 = count0 + 1; for(i = 7; i*i <= bound; i = i + 2) { count1 = count1 + 1; if (n % i == 0) { return 0; } } return 1; } function main() { var i, n, html = ''; n = 1000; for (i = 2; i < n; ++i) { if (prime(i)) { html += i + ' , '; } } document.writeln(html); console.log(count, count0, count1); } main();从980次减少到了265次!近3/4!大幅提高了程序的性能!
豆豆の爸爸对本书的所有笔记 · · · · · ·
> 查看全部3篇
说明 · · · · · ·
表示其中内容是对原文的摘抄