Why would reusing a DataContext have a negative performance impact?

前端 未结 4 1731
终归单人心
终归单人心 2020-12-14 10:02

After a fair amount of research and some errors, I modified my code so that it creates a new DataContext each time the database is queried or data is inserted. And the data

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-14 10:40

    Here's why re-using a DataContext is not a best practice, from the MSDN DataContext documentation:

    The DataContext is the source of all entities mapped over a database connection. It tracks changes that you made to all retrieved entities and maintains an "identity cache" that guarantees that entities retrieved more than one time are represented by using the same object instance.

    In general, a DataContext instance is designed to last for one "unit of work" however your application defines that term. A DataContext is lightweight and is not expensive to create. A typical LINQ to SQL application creates DataContext instances at method scope or as a member of short-lived classes that represent a logical set of related database operations.

    If you're re-using a DataContext for a large number of queries, your performance will degrade for a couple of possible reasons:

    1. If DataContext's in-memory identity cache becomes so large that it has to start writing to the pagefile then your performance will be bound to the HD's read-head speed and effectively there won't be a reason to use a cache at all.

    2. The more identity objects there are in memory, the longer each save operation takes.

    Essentially what you're doing is violating the UoW principle for the DataContext class.

    Opening database connections does have some overhead associated with it, but keeping a connection open for a long period of time (which often also means locking a table) is less preferable than opening and closing them quickly.

    Another link which may or may not help you from MSDN:

    How to: Reuse a Connection Between an ADO.NET Command and a DataContext (LINQ to SQL)

提交回复
热议问题