Groups | Blog | Home
all groups > dotnet general > march 2008 >

dotnet general : LINQ - Speed penalty/anonymous types


Jon Skeet [C# MVP]
3/31/2008 1:12:31 PM
[quoted text, click to view]

No. It's anonymous at compile time, but it's a perfectly ordinary type
as far as the CLR is concerned. All you're doing in the above is
calling a constructor and then retrieving properties.

Of course, in the above case you could just go directly to the members
of the list, but I'm assuming in real life that you actually have a
reason to use the anonymous type in the first place.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
Peter Larsen [CPH]
3/31/2008 2:00:44 PM
Hi,

I'm wondering if the use of anonymous types slow down the app at runtime or
not.

See the following sample:

var obj1 = from item in list select new { item.ClassID, AnyName
= item.ClassID };
foreach (var item in obj1)
{
string s1 = item.ClassID;
string s2 = item.AnyName;
}

I know lot of the work is done at compile time, but i still wondering if it
slows down the application to use anonymous types:
Is it slower to use ?

BR
Peter

Marc Gravell
3/31/2008 2:37:49 PM
In this case, with a list - it would be *slightly* more efficient to just
access each item in the list, since it avoids creating a short-lived object
per row - i.e.

foreach(var originalItem in list) {
// do something with originalItem.ClassID etc
}

However, if "list" is actually an IQueryable (or similar) source such as an
LINQ-to-SQL DataContext, then your original (projection-based) code would be
more efficient: in this case, the provider can usually do something clever -
i.e. with SQL it can build a SELECT statement that only includes the two
columns, and doesn't worry about change-tracking etc.

Marc

Peter Larsen [CPH]
3/31/2008 3:27:32 PM
Thanks for your comment.
It's just sample code - i'm not using it anywhere.

/Peter

[quoted text, click to view]

Peter Larsen [CPH]
4/1/2008 9:43:34 AM
Thanks for your comment Marc.

AddThis Social Bookmark Button