由于更多“for”循环导致性能问题。加载页面需要15-20秒。前三个for循环来自三个不同的JSON文件。
代码:
$scope.loading = function(item, scode) {
item.calling = [];
for (var i = 0; i < $scope.planMapping.length; i++) {
for (var x = 0; x < $scope.callplanList.length; x++) {
for (var z = 0; z < $scope.AHOfferScode.length; z++) {
if (($scope.planMapping[i].PlanScode == $scope.callplanList[x].un_s_code) &&
($scope.callplanList[x].offer_type == "REC") &&
($scope.callplanList[x].s_code == $scope.AHOfferScode[z])
) {
//console.log($scope.devicesList);
for (var a = 0; a < $scope.callplanList[x].upfront_cost.length; a++) {
item.calling.push($scope.callplanList[x]);
}
}
}
}
}
是否有替换“for”循环(过滤器或其他东西)以改善性能,如:
euPlanDeviceScodes. PlanScode = CallPlan.un_s_code
availableHandsetOfferScodes = CallPlan.s_code
CallPlan.offer_type = “REC”
答案 0 :(得分:1)
如前所述,像filter
这样的数组函数对于提高可读性非常有用,但却会降低性能。差异并不大,但如果您需要高性能代码,for
是最佳选择。
那就是说,你可以改善逻辑。
在你的循环中,你有一个条件,
$scope.callplanList[x].offer_type == "REC"
此条件不依赖于任何循环变量,可以在循环之前处理
$scope.loading = function(item, scode) {
item.calling = [];
var recOfferList = $scope.callplanList.filter((plan) => plan.offer_type === 'REC');
for (var i = 0; i < $scope.planMapping.length; i++) {
for (var x = 0; x < recOfferList.length; x++) {
for (var z = 0; z < $scope.AHOfferScode.length; z++) {
if (($scope.planMapping[i].PlanScode == recOfferList[x].un_s_code) &&
(recOfferList.s_code == $scope.AHOfferScode[z])
) {
//console.log($scope.devicesList);
for (var a = 0; a < recOfferList[x].upfront_cost.length; a++) {
item.calling.push(recOfferList[x]);
}
}
}
}
}
另一个优化的地方可能是最里面的循环:
for (var a = 0; a < $scope.callplanList[x].upfront_cost.length; a++) {
item.calling.push($scope.callplanList[x]);
}
以上代码未在正文中的任何位置使用a
。这可以替换为
item.calling = item.calling.concat(
new Array.fill($scope.callplanList[x].upfront_cost.length)
.fill($scope.callplanList[x])
)
或者如果您可以使用ES6功能,可以是Array.from
item.calling = item.calling.concat(
Array.from({
length: $scope.callplanList[x].upfront_cost.length
}, () => $scope.callplanList[x])
)
答案 1 :(得分:0)
使用find()而不是使用循环来检查if条件。它可能会限制循环
喜欢,
var array1= [1,2,3];
var array2= [3,4,5];
for(var i=0; i < array2.length;i++)
{
var matchedData = array1.find(function(x){ return x===array2[i]});
if(matchedData)
{
console.log(matchedData);
}
}
&#13;
现在你可以减少一个循环。同样的逻辑做到这一点。