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, cylindre is 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++)
    if (cylindre.IsPointInside(fpc.Vertices[i]))

    Version 2, with LINQ

    var insidePoint =
    from pt1 in fpc.Vertices
    where cylindre.IsPointInside(pt1)
    select pt1;

    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.

    In the LINQ version, you might consider using `AddRange()` instead of `foreach`. It won't increase performance, but it will make your code more readable. Also, using `Where()` directly will be shorter than `from`/`where`/`select`.

  • Xharze

    Xharze Correct answer

    9 years ago

    Under the hood LINQ will iterate over the collection, just as foreach will. 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.

    link is no longer valid

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM