Angular ng-if vs ng-switch 性能 [英] Angular ng-if vs ng-switch performance
问题描述
我在想 ng-if 或 ng-switch 哪个更快?假设我们有一个案例:10 个不同的 div,并且一次只需要一个.如果使用 ng-switch 而不是 ng-if,速度上有什么不同吗?
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?
如果使用 ng-if,所有元素将被单独评估,但 ng-switch 是否也这样做?
If ng-if is used all the elements will be evaluated separately, but does ng-switch do the same?
使用 angular 1.x
Using angular 1.x
推荐答案
ng-if 和 ng-switch 都创建了自己的作用域.所以在这一点上,没有区别.
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.
如果您只有几个元素,最好使用 ng-switch
变体,因为正如我在评论中所说,ng-switch
具有避免匹配所有可能值的好机会,因为在 angularjs 中不可能创建 if/else if/else if/else if
子句.使用 ng-if
,所有的 if 条件都会被评估.
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.
但是由于 ng-show 使元素在 DOM 中保持活动状态(与 ng-if
相反),这意味着即使用户没有看到它们的所有监视表达式和性能成本仍然存在完全查看.在非常大的视图中,这可能会带来惩罚.
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.
这篇关于Angular ng-if vs ng-switch 性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!