LINQ - Speed penalty/anonymous types

  • Thread starter Thread starter Peter Larsen [CPH]
  • Start date Start date
P

Peter Larsen [CPH]

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
 
Peter Larsen said:
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 ?

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.
 
Thanks for your comment.
It's just sample code - i'm not using it anywhere.

/Peter
 
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
 
Back
Top