[英]If filtering same data twice, why does Array.filter takes almost 10 times more time than $filter if executed at once?
我正在尝试比较angular的$ filter服务和javascript的Array.filter方法所花费的时间。
此问题仅在Chrome中可重现。
如果同时运行这两种方法,则每次使用一个过滤器比使用其他过滤器多花费近10倍的时间来过滤数组,但是如果我分别运行它们,则它们所花费的时间几乎相等。
使用Array.filter方法:-
arr.filter(function(a){
return ((a.buyout - 33333333) === 0);
});
使用$ filter:-
$filter('filter')(resp.alliance.auctions, function(data){
return ((data.buyout - 33333333) === 0);
});
这里有过滤器的任何缓存问题(或功能)吗?
与工作代码plnkr: - http://plnkr.co/edit/A5UeZK6Jnafp9SkVBxZi
代码优化将在这里发挥作用。 将首先执行的代码变体将首次访问返回的结构。 Chrome浏览器可能会节省一些资源第一次访问实际发生之前,但一旦你做作出这样的访问,浏览器必须随时进行数据访问。
当您更改实际执行的顺序时,例如通过将Array#filter
块包装在setTimeout
,您会注意到$filter
方法会消耗更多时间,而Array#filter
会赢。 因此,实际上,第一个执行的开销比第二个执行的开销大。
为了进行正确的比较,您必须先访问输入数组和$filter
而不用测量时间,然后才执行这两个变量,因此它们在相同情况下尽可能多地启动。
通过以下安排,时间消耗的差异非常小:
angular.module('myApp', []).controller('myCtrl', function($filter, $http, $scope){
$http.get('https://cors-anywhere.herokuapp.com/https://auction-api-eu.worldofwarcraft.com/auction-data/258993a3c6b974ef3e6f22ea6f822720/auctions.json').success(function(resp){
// Perform a dry run to make sure all resources are loaded:
var result = resp.alliance.auctions.filter(function(a){
return ((a.buyout - 33333333) === 0);
});
result = $filter('filter')(resp.alliance.auctions, function(a){
return ((a.buyout - 33333333) === 0);
});
var start = performance.now(), diffArrayFilter = 0, diff$filter = 0;
// Now start the real measurement
start = performance.now();
result = $filter('filter')(resp.alliance.auctions, function(a){
return ((a.buyout - 33333333) === 0);
});
diff$filter = performance.now() - start;
start = performance.now();
result = resp.alliance.auctions.filter(function(a){
return ((a.buyout - 33333333) === 0);
});
diffArrayFilter = performance.now() - start;
$scope.time = 'Time taken by $filter: '+diff$filter.toFixed(2)+' ms';
document.getElementById('aLength').innerHTML = 'Array Length: '+resp.alliance.auctions.length;
document.getElementById('fTime').innerHTML = 'Time taken by Array.filter: '+diffArrayFilter.toFixed(2)+' ms';
document.getElementById('fLength').innerHTML = 'Filtered Array Length: '+result.length;
});
});
查看您更新的插件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.