Array.prototype.swap = function(i, j) {
var temp = this[i];
this[i] = this[j];
this[j] = temp;
}

Array.prototype.quickSort = function(s, e) {
if (s == null) s = 0;
if (e == null) e = this.length - 1;
if (s >= e) return;
this.swap((s + e) >> 1, e);
var index = s - 1;
for (var i = s; i <= e; ++i) {
if (this[i] <= this[e]) this.swap(i, ++index);
}
this.quickSort(s, index - 1);
this.quickSort(index + 1, e);
} var a = [];
for (var x = 0; x < 20000; x++) {
a.push( Math.floor(Math.random()*20000));
}
a.quickSort();
代码生成20000个随机数进行排序
以上在Firefox下执行时间为 100毫秒代码2:var a = [];
for (var x = 0; x < 20000; x++) {
a.push(Math.floor(Math.random()*20000));
}
a.swap = function(i, j) {
var temp = this[i];
this[i] = this[j];
this[j] = temp;
}

a.quickSort = function(s, e) {
if (s == null) s = 0;
if (e == null) e = this.length - 1;
if (s >= e) return;
this.swap((s + e) >> 1, e);
var index = s - 1;
for (var i = s; i <= e; ++i) {
if (this[i] <= this[e]) this.swap(i, ++index);
}
this.quickSort(s, index - 1);
this.quickSort(index + 1, e);
}
a.quickSort();以上执行结果花了 250毫秒, 比原先多出100毫秒,  考虑到是动态生成的随机数,生成时的排列顺序可能影响速度,于是作了多组测试,结果都差不多请问是啥原因效率会差那么多?

解决方案 »

  1.   

    方法的实现是一样的.
    那就是到方法的运行时应该是没差别的.
    差别应该是出现在获取this.swap上.
    获取原型方法和对象方法的效率有少许差别.个人观点.楼下继续...
      

  2.   

    没仔细看代码.原因应该至少有二:1, 多了一层scope chain的开销.2,查找属性的过程实际是遍历, Array.prototype上的属性越多, 花的时间就有可能越多. 而a是一个相对干净很多的对象.
    其实还是一个数量级的开销, 不用太在意. 关键是确定为什么要循环20000次.
      

  3.   

    个人见解:
    prototype(他的每一个内部对象都在内存中北自动管理),而外部循环时计算机需要多一步操作,先声明一个指针,然后去寻找你需要判断的数内存地址。而为内部对象时此属性的全部指针都已存在,没有创建,没有搜索。循环时少一步操作。
      

  4.   

    我测了一下,只有在FF里面有差异,用下面的代码:
    //Array.prototype.aa = function()
    //{
    //    for(var i=0;i<1000000;i++)
    //    {
    //        this[i];
    //    }
    //}
    var array = [];
    //array.aa = function()
    //{
    //    for(var i = 0;i<1000000;i++)
    //    {
    //        this[i];
    //    }
    //}
    for(var i = 0;i<1000000;i++)
    {
        array[i] = i;
    }
    var date1 = new Date();
    array.aa();
    var date2 = new Date();
    alert(date2-date1);
    两部分注释分别运行,FF第二种方式消耗时间是第一种的5倍
    IE、opera、chrome时间都是相同,可以认为从js语法方面两种方式没有差别,其实也是怎么想他也不应该有差别,只能说明FF的js引擎有问题
    不同浏览器的js引擎差别很大,上面的代码IE需要360ms,chrome 10ms,opera 80ms,FF 55/280
    chrome还是很厉害的,真快啊