Is the LINQ version faster than the foreach one?
Since I don't know how LINQ works under the hood, I can't decide what version is best to use in term of rapidity of execution. I've done some testing with my testing data (Point Cloud) but I can't see a clear difference between the 2. The only thing I know is that the real life data will be a larger Point Cloud so my guess is that the LINQ would be faster but this is only if LINQ doesn't do a for each under the hood. If it's the case, the 2 functions would be the same. What is your advice?
By the way,
cylindreis a 3D cylinder and I want to know which point are inside.
Version 1 without LINQ
for (int i = 0; i < fpc.Vertices.Length; i++)
Version 2, with LINQ
var insidePoint =
from pt1 in fpc.Vertices
foreach (Point3D pt2 in insidePoint)
@ANeves Interesting article. I don't think my question in premature since this is in the requirement and very important because it will be done like 500 times a day by each user. And the only reason I don't have real data is that the final product isn't ready but I know for sure that it will be larger so optimization at this moment is very important. I'm also considering other way of improving the function but the difference between linq and the foreach was something that interest me.
Have you squeezed every bit of performance algorithmically? Which data structures and algorithms you use matters. Some highly optimized libraries for .Net will perform some computations faster. Also, perhaps it is possible to use PLINQ and utilize multiple cores at once? I would measure that too.
Thanks for the info. In fact, we have created a very small subset to run the foreach now it runs super fast, with LINQ and the foreach.
Under the hood LINQ will iterate over the collection, just as
foreachwill. The difference between LINQ and foreach is that LINQ will defer execution until the iteration begins.
Performance wise take a look at this blog post.
Just a note about that link. The link is dealing with deleting elements from a list. It uses a for loop, then contrasts that with a double foreach loop and a LINQ/foreach combo. Not really a fair comparison.
Also that link was three years old when this answer was posted, and is now over 11 years old.