Should I avoid LINQ for performance reasons?
-
Sound Code[^]:
Sometimes developers hear that "LINQ is slower than using a for loop" and wonder whether that means they should avoid using LINQ for performance reasons.
Or just the other reasons
I guess that should be reasons().other().or()?
-
Sound Code[^]:
Sometimes developers hear that "LINQ is slower than using a for loop" and wonder whether that means they should avoid using LINQ for performance reasons.
Or just the other reasons
I guess that should be reasons().other().or()?
im not gonna write a test to check this but 1. is there a difference of example linq, and writing 1 select. Having tried to write this, Im only 20% sure now if can be written close to the following☹️
Enumerable.Range(1, N).AsParallel()
.Select(n => {
var a = new {n * 2);
var b = Math.Sin((2 * Math.PI * a) / 1000))
var c = Math.Pow(b, 2) } )
.Sum();2. write Linq for readability instead the "depending on what for" performance.
-
im not gonna write a test to check this but 1. is there a difference of example linq, and writing 1 select. Having tried to write this, Im only 20% sure now if can be written close to the following☹️
Enumerable.Range(1, N).AsParallel()
.Select(n => {
var a = new {n * 2);
var b = Math.Sin((2 * Math.PI * a) / 1000))
var c = Math.Pow(b, 2) } )
.Sum();2. write Linq for readability instead the "depending on what for" performance.
To write:
Enumerable.Range(1, N).AsParallel()
.Select(n => n * 2)
.Select(n => Math.Sin((2 * Math.PI * n) / 1000))
.Select(n => Math.Pow(n, 2))
.Sum();with a single
Select
would be more like:Enumerable.Range(1, N).AsParallel()
.Select(n => Math.Pow(Math.Sin((4 * Math.PI * n) / 1000), 2) // 2 × PI × (n × 2) === 4 × PI × n
.Sum();However, it shouldn't make a huge difference. LINQ already optimizes
.Select(x => fn1(x)).Select(x => fn2(x))
to.Select(x => fn2(fn1(x)))
, so the only extra overhead would be from calling multiple delegates rather than just one.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer