Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is slice an impure pipe?

I've always believed that slice is pure and it's sole advantage over calling slice method on string or array is caching mechanism of pure pipes in Angular.

Turns out it isn't the case and slice is impure. Moreover implementation is very basic: it guards against nulls and delegates to slice method. No internal comparison of last transformed input.

I suspect it is designed to align with behavior of ngFor, but is it a viable reason? Newcomers would complain that Angular is broken otherwise I suppose, but then again why should I use this pipe?

Am I correct that it creates new arrays in every change detection run, which leads to triggering even OnPush change detection down the three and nullifying performance optimizations?

Edit: This question is based on assumption that one should use immutable data.

like image 480
Tomasz Błachut Avatar asked Jan 28 '23 11:01

Tomasz Błachut


1 Answers

This pipe is impure because it would otherwise return the same result until the array reference changes, so it wouldn't work when the array items change.

I personally think it is bad design to use such pipes. They removed the FilterPipe because of performance issues. Indeed, a pipe is triggered on every change detection, and there are many! I think the slice pipe should be removed as well. For me it's a quick and dirty solution, that brings more problems than it solves.

I suggest you slice your arrays yourself when needed.

like image 91
Guerric P Avatar answered Jan 31 '23 23:01

Guerric P