Anders
Anders

Reputation: 12560

Question about LINQ2Sql performance in C#

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!

Upvotes: 2

Views: 141

Answers (2)

Andrew Hare
Andrew Hare

Reputation: 351506

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.

Upvotes: 3

user151323
user151323

Reputation:

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

Upvotes: 2

Related Questions