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!
The
usingstatement 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 implementsIDisposableit really ought to be wrapped in ausingstatement 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
usingstatement will take longer to run. But this does not mean that you shouldn’t have theusingstatement. I think that you should use theusingstatement 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
usingstatement on types that implementIDisposableregardless of the fact that theusingstatement 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.