5

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

Firze
  • 3,939
  • 6
  • 48
  • 61
  • 1
    10 divs?! This is the definition of [premature optimisation](https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil). You should be more conrned about which one reads best *[Any fool can write code that a computer can understand. Good programmers write code that humans can understand.](https://en.wikiquote.org/wiki/Martin_Fowler)* – Liam Jun 16 '17 at 08:05
  • 2
    I would think that `ng-switch` has slightly better performance because it has a good chance not all values are matched. Because it is not possible in angularjs to create an *if / else if / else if / else if* clause, all if conditions always evaluated. Other than that, `ng-if` and `ng-switch` behave very much the same in terms of scoping etc. – Nico Van Belle Jun 16 '17 at 08:05
  • 1
    @Liam Obviously this ain't my entire use case. I just simplified it for the question. I got repeaters with potentially thousands of elements and each of these elements contain a few cases like this. And I am not expecting any massive performance gains. I'd like to know which is better. – Firze Jun 16 '17 at 08:13
  • Better makes no sense? They have different uses cases. If your not expecting any massive performance gains why are you even bothering? Just use which ever one reads best. This is 100% premature optimisation... – Liam Jun 16 '17 at 08:15
  • 1
    Because I am curious – Firze Jun 16 '17 at 08:27

2 Answers2

5

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.

Emad Dehnavi
  • 3,262
  • 4
  • 19
  • 44
5

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.

Nico Van Belle
  • 4,911
  • 4
  • 32
  • 49