-1

I have some queries that look like this:

public List<AnObjectModel> GetObjectFromDB(TheParameters)
{
   using MyDataContext
   {
     var TheList = (....select new AnObjectModel()...).ToList();
     return new List<AnObjectModel>(TheList);
   }
}

And they work just fine. My question is this: at the moment, I'm using var and then I'm doing a cast. Would doing this have any performance benefit?

   public List<AnObjectModel> GetObjectFromDB(TheParameters)
    {
       using MyDataContext
       {
         List<AnObjectModel> TheList = (....select new AnObjectModel()...).ToList();
         return TheList;
       }
    }

It would take me about 20 minutes to make the changes and I'm wondering if there'd be any difference.

Thanks.

frenchie
  • 51,731
  • 109
  • 304
  • 510
  • Possible duplicate of http://stackoverflow.com/questions/356846/c-sharp-var-vs-specific-type-performance – Matten Feb 01 '12 at 13:15

5 Answers5

7

You're not using a cast - you're creating a new list. That's definitely pointless, given that you've already got a freshly-created List<T>. I would just write:

return (....select new AnObjectModel()...).ToList();

Or quite possibly:

var query = from ...
            select new AnObjectModel { ... };
return query.ToList();

That avoids having to bracket the query expression, which generally looks ugly.

Edit according to taste for layout, but definitely remove the redundant list creation.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

It's completely useless. TheList already as a List<AnObjectModel>, because var is inferred by the compiler, meaning the runtime doesn't see any difference.

In other words:

List<AnObjectModel> TheList = (....select new AnObjectModel()...).ToList(); and var TheList = (....select new AnObjectModel()...).ToList(); are the same code.

The change you are thinking about making would make your performance worse, because you would create a second list and copy all the content from the first list to the second one!

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
0

var is a compile time operation which is why your intellisense still works properly. Using var vs List is the same thing at runtime. Removing the creation of the list from the original list would more than likely improve performance though.

Mark Smith
  • 1,085
  • 8
  • 19
0

Your second example implies that you already get a list of type List<AnObjectModel> as a return type. (Because in the second example you make no cast)

So you can do

public List<AnObjectModel> GetObjectFromDB(TheParameters)
{
   using MyDataContext
   {
     return (....select new AnObjectModel()...).ToList();
   }
}
Viper
  • 2,216
  • 1
  • 21
  • 41
0

You're not casting, you're calling the copy constructor of list which means you are making a copy of the list and returning the copy. So yes, it's faster to return the list directly than returning its newly created copy.

Thierry Ybt
  • 171
  • 1
  • 9