Search code examples
angularngforangular-ng-ifproperty-binding

Is it ok to use the function Map.prototype.get() inside an Angular Template Expression?


I know that you should never use function calls within Angulars Template Expressions, otherwise they will be called permanently and the app will be extremely stressed. (see Medium - Why You Should Never Use Function Calls In Angular Template Expressions)

I also know that it is ok, when the []-array-operator is used. e.g.

<div *ngIf="array[i]"></div>

Does anyone know if it is ok to use the function Map.prototype.get() inside a template expression like this?

<!-- the Map is structured like Map<Object, Object[]> -->
<ng-container *ngFor="let elem of someMap.get(keyToAnArray)">
    <app-some-compo [elem]="elem"></app-some-compo>
</ng-container>

Solution

  • Angular documentation states that it's possible to write complex template expressions in template, but it's a better practice to avoid them if those expressions don't finish quickly. It means that we should avoid long executable computation in templates.

    The reason is that Angular compiles templates into executable pieces of code that are executed during each change detection cycle. And if you have already been working for a while with Angular you should notice how many change detection cycles are executed in app.

    So, taken your template:

    *ngFor="let elem of someMap.get(keyToAnArray)"
    

    we will have smth like:

    component factory

    // part of change detection code starts here
    ...
    i0.ɵɵproperty("ngForOf", ctx.someMap.get(ctx.keyToAnArray));
    ...
    

    The main question we need to answer is: How fast is Map.prototype.get() method?

    From the specification:

    Map object must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements in the collection.

    In other words, we can think of Map as of implementation for Hash Table data structure. It should work super fast. But the speed of executing get method depends on the number of elements in the collection.

    The more elements you have the slower will be search. But in case of hash table structure I think it's just micro optimization.

    Conclusion:

    If you work on micro-optimization and have enormous amount of elements in your collection then consider moving this computation to dedicated component property. Otherwise just live with it.