Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更多for循环导致的性能问题_Javascript_Angularjs - Fatal编程技术网

Javascript 更多for循环导致的性能问题

Javascript 更多for循环导致的性能问题,javascript,angularjs,Javascript,Angularjs,因为更多的“for”循环会导致性能问题。加载页面需要15-20秒。前三个for循环来自三个不同的JSON文件 代码: 如前所述,像filter这样的数组函数有助于提高可读性,但会以性能为代价。差别不大,但如果您想要性能代码,for是最佳选择 也就是说,您可以改进逻辑 在你的循环中,你有一个条件 $scope.callplanList[x].offer_type == "REC" 此条件不依赖于任何循环变量,可以在循环之前进行处理 $scope.load=函数(项,scode){ item.ca

因为更多的“for”循环会导致性能问题。加载页面需要15-20秒。前三个for循环来自三个不同的JSON文件

代码:


如前所述,像
filter
这样的数组函数有助于提高可读性,但会以性能为代价。差别不大,但如果您想要性能代码,
for
是最佳选择

也就是说,您可以改进逻辑

在你的循环中,你有一个条件

$scope.callplanList[x].offer_type == "REC"
此条件不依赖于任何循环变量,可以在循环之前进行处理

$scope.load=函数(项,scode){
item.calling=[];
var recOfferList=$scope.callplanList.filter((plan)=>plan.offer_type===='REC');
对于(变量i=0;i<$scope.planMapping.length;i++){
对于(var x=0;x

另一个优化的地方可以是最里面的循环:

for(var a=0;a<$scope.callplanList[x].upfront\u cost.length;a++){
item.calling.push($scope.callplanList[x]);
}
上述代码未在正文中的任何位置使用
a
。这可以替换为

item.calling=item.calling.concat(
新建数组.fill($scope.callplanList[x].upfront\u cost.length)
.fill($scope.callplanList[x])
)
或者,如果您可以使用ES6功能,可以是
Array.from

item.calling=item.calling.concat(
Array.from({
长度:$scope.callplanList[x].upfront_cost.length
},()=>$scope.callplanList[x])
)
使用而不是使用循环来检查if条件。它可能会限制循环

var数组1=[1,2,3];
var array2=[3,4,5];
对于(变量i=0;i}
替换“for”循环(过滤器或其他东西)以提高性能没有。
。过滤器和其他功能是为了使代码更可读,但它们以性能为代价。没有任何功能可以与
for
的性能相匹配/优于。我的建议是尝试改进算法。例如
$scope.callplanList[x].offer_type==“REC”
可以提前完成。这将减少一些迭代。请确认代码var recOfferList=$scope.callplanList.filter((plan)=>plan.offer_type==“REC”);
plan
指的是正常for循环中的
.callplanList[x]
euPlanDeviceScodes. PlanScode = CallPlan.un_s_code
availableHandsetOfferScodes = CallPlan.s_code
CallPlan.offer_type = “REC”
$scope.callplanList[x].offer_type == "REC"