今天写基础库函数each时,看到jquery1.7.2中是分开两种方式执行回调的:call和apply,注释中说call会快些,于是在http://jsperf.com/做了如下测试
普通测试代码:
![](https://img-my.csdn.net/uploads/201208/06/1344264721_4457.png)
测试结果:
![](https://img-my.csdn.net/uploads/201208/06/1344264761_1297.png)
从这个普通例子来看,call的性能在某些浏览器下要明显比apply好,而其他浏览器中两者差别不大。
再来测试一下each方法:
测试代码:
![](https://img-my.csdn.net/uploads/201208/06/1344264809_5208.png)
注:上述代码中去掉了isFunction检查。
call测试:test(["1", "2", "3"],function(){})
apply测试:test(["1", "2", "3"],function(){})
测试结果:
![](https://img-my.csdn.net/uploads/201208/06/1344264837_4822.png)
由此可以看出call方法性能的优越性相当明显。
那么,是什么原因导致两个不同的测试结果呢?
我们再做一下几组测试:
1.带有参数,this指向null:
![](https://img-my.csdn.net/uploads/201208/06/1344264867_3671.png)
![](https://img-my.csdn.net/uploads/201208/06/1344265225_9389.png)
2.this不指向null,不带参数:
![](https://img-my.csdn.net/uploads/201208/06/1344264985_8856.png)
![](https://img-my.csdn.net/uploads/201208/06/1344264965_8628.png)
3.有this也有参数:
![](https://img-my.csdn.net/uploads/201208/06/1344264925_2601.png)
![](https://img-my.csdn.net/uploads/201208/06/1344264942_8415.png)
综合上述结果(时间关系,并不是所有示例都测试了一样多的浏览器,不过,基本覆盖了ie、ff、chrome),可以看出,当有this指向或者执行参数时,call的性能要明显优于apply。