zoukankan      html  css  js  c++  java
  • [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;
      }
    
    }
    {{entry.points | Rating }}
  • 相关阅读:
    机房收费系统——视图的运用
    POJ 3278: Catch That Cow
    LeetCode 66 Plus One(加一)(vector)
    iOS定位服务CoreLocation
    Python 多线程
    LuaStudio编辑调试软件
    高仿快递100--实战之RadioGroup和RadioButton应用
    HDU
    MVC项目中怎样用JS导出EasyUI DataGrid为Excel
    调用getChildFragmentManager时出现的Bug
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8987388.html
Copyright © 2011-2022 走看看