Angular ng-if vs ng-switch performance

2020-07-22 17:03发布

问题:

I was thinking which one is faster ng-if or ng-switch? Let's say we have a case: 10 different divs and only one is needed at a time. Is there any difference in speed if ng-switch is used instead of ng-if?

If ng-if is used all the elements will be evaluated separately, but does ng-switch do the same?

Using angular 1.x

回答1:

Both ng-if and ng-switch create their own scope. So at this point, there is no difference.

In the end, I think it pretty much depends on the use case.

If you have just a couple of elements, it would be probably better to use the ng-switch variant because, as put in my comment, ng-switch has a good chance to avoid matching all possible values as it is not possible in angularjs to create an if / else if / else if / else if clause. Using ng-if, all if conditions are always evaluated.

BUT Since ng-show leaves the elements alive in the DOM (in contrast to ng-if), it means that all of their watch expressions and performance cost are still there even though the user doesn’t see the view at all. In very large views, that can come with a penalty.



回答2:

ng-if is a ng-switch itself, the difference is only here that ng-if have only single expression.

so if you have only one expression it's better to use ng-if , otherwise use ng-switch. that's the only thing that you need to consider for using any of them.