Filtering a list of vertices that lie inside a cylinder, with and without LINQ

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 two. 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]))
        listPoint.Add(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)
    {
        listPoint.Add(pt2);
    }

Answer

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.

Attribution
Source : Link , Question Author : Jean-François Côté , Answer Author : Sᴀᴍ Onᴇᴌᴀ

Leave a Comment