当我 return 一个新数组时显着的性能损失

Significant performance loss when I return a new array

我有以下代码。

<div *ngFor="let item of items"></div>

这个渲染速度很快。然后我这样做了:

getItems() {
    return this.items;
}

<div *ngFor="let item of getItems()"></div>

这也是高性能的。然而,这个:

getItems() {
    return this.items.filter(item => item.premium === true);
}

<div *ngFor="let item of getItems()"></div>

运行速度很慢。我有什么想法可以提高过滤逻辑的性能,以及为什么我在返回新数组时性能损失很大?

getItems() 函数 returns 每次调用时都会生成一个新数组,因此 *ngFor 循环是 运行 每个 ngDoCheck 生命周期并且重新呈现整个内容。您需要保持对返回数组的相同引用,因此作为解决方案,您可以在初始化组件时调用一次此函数并将结果保存在变量中并在之后使用它。

你可以这样试试

1> 如果您的数组每秒或每分钟更改一次,则使用 trackBy 因此它仅更改值更改

的 DOM 元素

html

<div *ngFor="let data of myArray; trackBy: trackFunction" >
            {{data}}
</div>

TS

trackFunction(index, data) {
   if (!data) return null;
   return data
}

2> 您也可以使用 async 管道

直接订阅该数组

TS

apiCall() {
  this.myArray = this.service.getData(); // here this service return the observable 
}

HTML

<div *ngFor="let data of myArray | async"> 
{{data}}
</div>