Stepping up a level to C#, we have a couple of idiomatic solutions. Many C# programmers today might use Linq which as you can see is much slower. It also creates a lot of garbage, putting more pressure on the garbage collector. Oddly, the Aggregate function, which is equivalent to fold or reduce in most other languages, is slower despite being a single step instead of two. The foreach loop in the second example is also commonly used. While this pattern has big performance pitfalls when used on collections like List<T>, with arrays it compiles to efficient code. This is nice as it saves you some typing without runtime penalty. The runtime here is still twice as slow as the C code, but that is entirely due to not being automatically vectorized.
"Much slower" here meaning 300 ms instead of 30 -- a 10x difference but still under a second. And part of the appeal of Linq is that a functional approach is generally less error-prone, which is why there is a lot of interest these days in immutable data structures even though they're obviously less efficient.
There's nothing wrong with this kind of test but some perspective is warranted.
1
u/RICHUNCLEPENNYBAGS May 26 '19
"Much slower" here meaning 300 ms instead of 30 -- a 10x difference but still under a second. And part of the appeal of Linq is that a functional approach is generally less error-prone, which is why there is a lot of interest these days in immutable data structures even though they're obviously less efficient.
There's nothing wrong with this kind of test but some perspective is warranted.