平时写js常常遇到这样作是否是更快点?但又没有具体简单可测试的工具,最近也倒序看博客园司徒正美 js分类下的文章html
【ps:去年灵光一闪,发现看博客园排名前100的博客、按照文章分类倒序看是学习最快的方式 O(∩_∩)O~】浏览器
看到这篇文章时 (转)Google Closure: 糟糕的JavaScript http://www.cnblogs.com/rubylouvre/archive/2009/12/07/1615593.htmlruby
文中有些 性能优化对比的举例,让我想起去年我寻找js性能基准测试工具、jsdom操做测试工具、js单元测试工具性能优化
今天分享下我找的一个js性能基准测试工具---JSLitmus闭包
JSLitmus是一个轻量级的工具,用于建立针对性的JavaScript基准测试工具dom
JSLitmus 有不少优势 简单易用、1分钟就学会了函数
这是官网地址:http://www.broofa.com/Tools/JSLitmus/工具
官网例子 2 http://www.broofa.com/Tools/JSLitmus/demo_test.html 这个里面有不少测试用例 O(∩_∩)O~oop
使用JSLitmus 作性能基准测试的基本步骤性能
建立一个静态页,引入JSLitmus.js ,而后调用JSLitmus 的基本方法就能够了 例如
<script src="JSLitmus.js"></script> <script> JSLitmus.test('Empty function test', function() {}); </script>
这个空的执行函数会显示每秒实行无数次
这个函数还能够传递一个参数,官网说的我不是很明白,大概意思是经过传递这个参数能够获取更加准确的执行结果.,
经过count能够细节的控制循环,(ps:我的感受就是由本身控制循环…)
JSLitmus.test('a non-looping test', function(count) { while (count--) { // Your test code goes here } });
这个性能基准测试工具能够看到
1 使用内存的状况,
2多长时间内执行了多少次
我的感受这两个指标基本够用了,并且支持多浏览器,对与ie浏览器,执行时间太长会出现卡死,须要特殊配置,具体配置文章结束再说
这里能够看一下官网举得例子
1 测试对全局变量进行访问和修改的性能
// First, test a variable in the global scope var global_var = 1; JSLitmus.test('global', function(count) { while (count--) global_var++;} );
2测试对局部变量进行访问和修改的性能
// Now test one that's in a function's local scope JSLitmus.test('local', function(count) { var local_var = 1; while (count--) local_var++; });
3测试在一个闭包中,对上一级变量进行访问和修改的性能
// Try a variable bound to a closure function. Prototype and JQuery developers // should find this particularly interesting. JSLitmus.test('closure', (function() { var closure_var = 1; return function(count) {while (count--) closure_var++;} })() );
4两次闭包,最里面的闭包访问爷爷级别的变量的性能【ps:做者太奇葩这样的函数写出来,不过这里count咋用我学会了。。】
// Closure binding again, but this time with the variable bound through nested // closures. JSLitmus.test('multi-closure', (function() { var multi_var = 1; return (function() { return function(count) {while (count--) multi_var++;} })() })() );
5测试对一个引用空函数表达式的调用
// Test an empty function call, which we can use as a reference point JSLitmus.test('empty function call', function(count) { var f = function() {}; while (count--) f(); });