views:

96

answers:

2

Hey SO:

From a performance perspective, is it better to wrap each statement that utilizes LINQ in a using() statement, or to declare a class-level instance and use in each method?

For instance:

public void UpdateSomeRecord(Record recordToUpdate)
{
    using(var entities = new RecordDBEntities())
    {
     // logic here...
    }
}


private RecordDBEntities entites = new RecordDBEntities();
public void UpdateSomeRecord(Record recordToUpdate)
{
    // logic here...
}

Or does it not matter either way?

Thanks!

+2  A: 

In fact your question is about the lifetime management of the LINQ DataContext.

You may wish to look at the following article: Linq to SQL DataContext Lifetime Management

Developer Art
thanks for the link! will read :)
Anders
+3  A: 

The using statement may hurt performance in the sense that it will take longer to run but this shouldn't be your concern in cases like this. If a type implements IDisposable it really ought to be wrapped in a using statement so that it can clean up after itself.

This cleanup code will take longer to run than no cleanup code of course so that is why I say that the using statement will take longer to run. But this does not mean that you shouldn't have the using statement. I think that you should use the using statement even though it may take longer to run.

I guess what I am trying to say is that you are comparing apples to oranges here as performance comparisons only make sense when the code being compared creates identical output and identical side effects. Your examples do not so that I why I don't think this is a performance issue.

The best practice in this situation is to use the using statement on types that implement IDisposable regardless of the fact that the using statement will make the method run longer. If you need to know how much longer it will run then you should employ a profiler to identify if the code in question is creating a bottleneck.

Andrew Hare
OK that sort of makes sense. The code I posted is from an Interface I am building, but it does not implement the dispose method. I suppose I could add it and call it in the main section, but from what you are saying it would be better in the long run to wrap each segment in its own Using statement to take care of the disposing, correct?
Anders
I imagine my question was poorly formed. Maybe best practices instead: What is the best practice for LINQ queries in C#?
Anders
Don't *add* an implementation of `IDisposable` if one does not already exist and is not needed. If you don't need to dispose of any unmanaged resources then your don't need the interface! :)For more info please read http://msdn.microsoft.com/en-us/library/system.idisposable.aspx.
Andrew Hare