C # - foreach loop - good practice

Is this good or bad:

foreach (Match match in serverNameRegex.Matches(loginPage)) { .... } 

or should I use it to improve speed:

 MatchCollection matches = serverNameRegex.Matches(loginPage); foreach (Match match in matches) { ... } 
+4
source share
7 answers

While MatchCollection cannot be null, I would say that this is your choice.

But if it turns out to be null and you don’t check it in advance, you will encounter a NullReferenceException .

+6
source

There is no difference in speed. This is just a matter of style.

In both cases, an IEnumerator is created using the GetEnumerator() method. This happens only once. In each subsequent record of the loop, only the MoveNext() method will be called.

+3
source

The second may be preferred since:

  • You can easily send a breakpoint after it to track it (debugging)
  • If you need to make changes, you also do not change the cycle (which should not be affected).
  • Easier to read
  • Mismatch if you want to add checks before the loop
+3
source

I prefer the latter, although there is no difference between them. Because the second seems clearer, and you can easily add more in the future.

 MatchCollection matches = serverNameRegex.Matches(loginPage); foreach (Match match in matches) { } //do something to matches in the future 
+3
source

this does not make a difference, but I say that the second one is more understandable, cleaner and easier to read the first.

Use a deassembler or a reflector to check the details.

and for the second it’s useful if you want the user matches collect after the foreach loop.

+1
source

It depends if you need matches elsewhere in your code. I think it would be easier to use

 foreach (Match match in serverNameRegex.Matches(loginPage)) { } 

because it will clear the variable after loop completion

+1
source

There is a speed difference between the two and the first:

  foreach (Match match in serverNameRegex.Matches(loginPage)) { .... } 

works faster.

The reason is that in the first case, serverNameRegex.Matches (loginPage) is evaluated once, and the for loop already knows about each matching value, whereas in:

  MatchCollection matches = serverNameRegex.Matches(loginPage); foreach (Match match in matches) { ... } 

the loop should evaluate the collection of matches at each iteration.

-2
source

Source: https://habr.com/ru/post/1385076/


All Articles