I wondered what the performance overhead is of using Enumerable.Range
was against using a foreach
loop. For example:
var stringArray = Enumerable.Range(0, 4).Select(i => string.Empty).ToArray();
VS.
var stringArray = new string[4];
for (int i = 0; i < formatted.Length; i++)
{
stringArray[i] = string.Empty;
}
I spotted these question:
But I fear with the Select
at the end then I might be, in effect, loop twice. However I like the elegance of using the Range
option.
In my very simple test it looks like for loop is faster by 38ms for 1 000 000 strings.
From the following test the
for
is more efficient: (in milliseconds it is +-3 ms difference - which is insignificant..)But you can instead of using
Enumerable.Range().Select
use.Repeat
:After saying the above notice that you are talking here about very small collections (4 items). In larger collections, and especially if you remove the
.ToArray()
it doesn't behave the same:Looking though the Reference Source both the
.Range
andRepeat
are implemented with ayield return
:So it too id deffered executed, just like the
.Select
meaning it does not loop twice.Not that the use of the
Stopwatch
returns different results each run but the overall idea is as presented aboveIMO, especially in the case of small collections go for readability over hese minor performance improvements. When you already hit performance issues, only after getting the bigger fish (for instance nested
for
loops onList<>
instead of using aHashSet<>
), deal with stuff like this.