jackmott / LinqFaster

Linq-like extension functions for Arrays, Span<T>, and List<T> that are faster and allocate less.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

loop type

jnyrup opened this issue · comments

The extension methods in e.g. Sum.cs uses foreach for arrays and C-style loops for Lists, just as the benchmarks tells us.
Others such as Min.cs does not follow this practice.

For C-style loops a quick grep finds 101 occurrences with Lists and 122 occurrences for arrays.

foreach performs identically on arrays, so it is ok to use there.

In Min.cs, some of the loops don't start at 0 so we can't use foreach.

Are you seeing any cases where there would be a performance impact or just looking for consistency of style?

As the library seems quite focused on performance, I searched for places for even the slightest gain and the article does mention a .1 µs difference for using foreach vs C-style loops for arrays.

There are 45 occurrences of for (int i = 0; i < source.Length; i++) and for a few samples, the index wasn't used.
E.g in Min.cs

I haven't done any benchmarks to test the actual difference, and if you prefer to avoid switching loop types to much, that's no problem.

I'll check the compiled IL of each in a little bit to confirm or deny if there is really a difference in how it compiles. The 1us difference may just be noise. I'll find out. Thanks.

I've double checked and confirmed that foreach and for loops perform the same with arrays, at least under RyuJIT. I can check and confirm if this is true under mono as well.

You shouldn't do it for my sake.
I'm convinced.