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.
source share