[Angular] Increasing Performance by using Pipe


For example you make a function to get rating;

getRating(score: number): string {
    let rating: string;
    console.count('RatingPipe');
    if(score > 249000){
      rating = "Daniel Boone";
    }
    else if(score > 200000){
      rating = "Trail Guide";
    }
    else if(score > 150000){
      rating = "Adventurer";
    }
    else if(score > 100000){
      rating = "Pioneer";
    }
    else if(score > 50000){
      rating = "Greenhorn";
    }
    else{
      rating = "Buzzard food";
    }
    return rating;
  }

Then using it in html:

{{getRating(entry.points)}}

These code actually casues the preformance issues, because everything Angualr's change detection run, it saw function call inside {{}}, it have to run it everything when anything changes, there is no way to figure out whether the function output changes or not without running it.

The way to fix it is using Pipe. Angular will remember the input value and cache the output. Therefore by using pipe we can reduce the number of function call way better.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'Rating'
})
export class ScoreRatingPipe implements PipeTransform {

  transform(score: number): string {
    let rating: string;
    console.count('RatingPipe');
    if(score > 249000){
      rating = "Daniel Boone";
    }
    else if(score > 200000){
      rating = "Trail Guide";
    }
    else if(score > 150000){
      rating = "Adventurer";
    }
    else if(score > 100000){
      rating = "Pioneer";
    }
    else if(score > 50000){
      rating = "Greenhorn";
    }
    else{
      rating = "Buzzard food";
    }
    return rating;
  }

}

长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn