[原创][开源]跨浏览器的JavaScript性能检测工具 - 至于你信不信,我反正信了

来源:互联网 发布:阿里云ecs安装tomcat 编辑:程序博客网 时间:2024/04/29 12:36

提出问题

如果识别出页面中JavaScript函数的性能问题,在不同浏览器下有不同的测试工具:

  • Firefox下使用Firebug的Profile工具

    Firefox Profile Tool

  • Chrome下使用内置的Profile工具

    Chrome Profile Tool

  • IE9下也有Profile工具

    IE9 Profile Tool

虽然大家的功能一个比一个炫,但是始终解决不了两个问题:

  • 如何只检测指定命名空间下的函数性能,否则会产生大堆的无用数据。
  • 不能跨浏览器使用,没有统一的参照物。同时不同工具之间还有一定差异的背景噪音影响。

还有一点就是仍然占据主流的IE7和IE8没有内置的JavaScript性能检测工具。

寻求解决方案

首先在网上找到的一篇文章是John Resig在2008年6月发表的一篇文章,是够古老的了,不过还是非常有借鉴意义,它的输入结果如下所示:

John Resig getProfile

我们来看一下它的核心代码,这段代码用来处理jQuery.fn下的所有函数:

for (var method in jQuery.fn)(function (method) {
   
if (method == "init") return;

   
var old = jQuery.fn[method];

    jQuery
.fn[method] = function () {
       
if (!internal && curEvent) {
           
internal = true;
           
var m = curEvent.methods[curEvent.methods.length] = {
                name
: method,
                inLength
: this.length,
                args
: formatArgs(arguments)
           
};
           
var start = (new Date).getTime();
           
var ret = old.apply(this, arguments);
            m
.duration = (new Date).getTime() - start;

           
if (curEvent.event == "inline") curEvent.duration += m.duration;

           
if (ret && ret.jquery) m.outLength = ret.length;
           
internal = false;
           
return ret;
       
} else {
           
return old.apply(this, arguments);
       
}
   
};
})(method);

从这段代码中,我们看到如下一些步骤:

  1. 将需要处理的函数备份起来:var old = jQuery.fn[method];
  2. 使用一个新的函数覆盖此函数:jQuery.fn[method] = function () {
  3. 在新函数内,调用备份的原始函数,并在调用前后添加计时代码,以确定本次调用这个原始函数的时间:

    var start = (new Date).getTime();var ret = old.apply(this, arguments);m.duration = (new Date).getTime() - start;

有了这个核心概念,我们可以写个自己的JavaScript的Profile功能,而不仅仅是局限于检测jQuery代码,我们要让用户自己指定要检测的JavaScript命名空间!

我的开源实现

我的开源实现:http://code.google.com/p/jprofile/

它的最大特点:

  1. 可以指定测试的命名空间
  2. 可以跨浏览器使用

使用起来非常方便,只需要如下几个步骤:

  1. 在页面的最后引入jprofile.js。(这也是安装jprofile开源解决方案的全部步骤!

    Enable jProfile 1

  2. 打开页面,可以看到右上角的那个Enable jProfile按钮:

    Enable jProfile 2

  3. 点击那个按钮,会弹出一个对话框,输入你要检测的命名空间,比如"jQuery":

    Enable jProfile 3

  4. 点击确定,页面会自动刷新,并显示jProfile工具条。点击Display按钮显示结果:

    Enable jProfile 3

跨浏览器测试jQueryUI

下面就让我们使用jProfile测试一下jQueryUI首页JavaScript的性能,以下是测试数据。你可以自己试一下,在线示例地址。

  • Firefox

    jQueryUI with jProfile Firefox

  • IE7

    jQueryUI with jProfile Firefox

  • IE8

    jQueryUI with jProfile Firefox

这是个跨浏览器JavaScript性能检测的奇迹,至于你信不信,我反正信了。