LINQ2Sql performance question in C #

From a performance standpoint, is it better to wrap every statement that uses LINQ in a using () statement, or declare an instance of the class and use it in every method?

For example:

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 anyway?

Thank!

+2


source to share


2 answers


The operator using

can hurt performance in the sense that it will take longer, but this should not bother you in such cases. If the type implements IDisposable

, it really needs to be wrapped in a statement using

so that it can clean up after itself.

This cleanup code will take longer than without the cleanup code, so I say the instruction using

will take longer. But that doesn't mean you shouldn't have an operator using

. I think you should use the operator using

, although it may take longer.



I guess what I'm trying to say is that you are comparing apples to oranges here, since the performance comparison only makes sense when the code being compared produces an identical result and identical side effects. Your examples are wrong, that somehow I don't think this is a performance issue.

The best practice in this situation is to use an operator using

for types that implement IDisposable

, regardless of whether the operator using

will cause the method to run longer. If you need to know how long it will run, then you should use a profiler to determine if this code is creating a bottleneck.

+3


source


In fact, your question is about LINQ DataContext lifecycle management.



You can see the following article: Linq to SQL DataContext Lifetime Management

+2


source







All Articles