underscore源码效率问题

对underscore的调用过程还是不太明白呢,如下:
调用方式一:

var iterations = 1000000;console.time('#optimizeCb');for(var i = 0; i < iterations; i++ ){
  _.each([1,2,3],function(val,key){});
};console.timeEnd('#optimizeCb')

VM57585:7 #optimizeCb: 1791.113ms

调用方式二:

var iterations = 1000000;console.time('#optimizeCb');for(var i = 0; i < iterations; i++ ){
  _([1,2,3]).each(function(val,key){});
};console.timeEnd('#optimizeCb')

VM57586:7 #optimizeCb: 2332.177ms

为啥效率差别这么大,第二种慢主要是因为有实例化过程吗?希望大神指教呀?


慕桂英3389331
浏览 491回答 1
1回答

30秒到达战场

看着好像是实例化问题,但是如果代码这样写的话:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var iterations = 1000000;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.time('#init');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var obj = _([1,2,3]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.timeEnd('#init');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.time('#optimizeCb0');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(var i = 0; i < iterations; i++ ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; obj.each(function(val,key){});&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.timeEnd('#optimizeCb0')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.time('#optimizeCb');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(var i = 0; i < iterations; i++ ){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _.each([1,2,3],function(val,key){});&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.timeEnd('#optimizeCb');assign:20&nbsp;#init:&nbsp;0.000msassign:25&nbsp;#optimizeCb0:&nbsp;492.000msassign:30&nbsp;#optimizeCb:&nbsp;223.000ms看输出的时间,实例化貌似问题不大,重点在于调用_.each跟_().each的区别我没用过后者,跟踪了一下源码看其实现:&nbsp;// Helper function to continue chaining intermediate results.&nbsp; var result = function(instance, obj) {&nbsp; &nbsp; return instance._chain ? _(obj).chain() : obj;&nbsp; };&nbsp; // Add your own custom functions to the Underscore object.&nbsp; _.mixin = function(obj) {&nbsp; &nbsp; _.each(_.functions(obj), function(name) {&nbsp; &nbsp; &nbsp; var func = _[name] = obj[name];//这里遍历的时候 name 有为each的时候&nbsp; &nbsp; &nbsp; _.prototype[name] = function() {//当name='each'时,_的原型就有了each方法,此时func=_.each&nbsp; &nbsp; &nbsp; &nbsp; var args = [this._wrapped];&nbsp; &nbsp; &nbsp; &nbsp; push.apply(args, arguments);&nbsp; &nbsp; &nbsp; &nbsp; return result(this, func.apply(_, args));&nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; });&nbsp; };从这里也可以看出_().each实际上底层也是用了_.each,但是人家不是直接用,还多了一些赋值啊,数组push等操作,我想后者多花的时间应该出自这些操作吧。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript