Why SaveChanges method takes up memory?

1k views Asked by At

While preparing large amount (several thousand rows) of data and insert them to database through Entity Framework, creating the Entity objects or the in-memory object-graphs doesn’t take up that much memory, but when the SaveChanges() method is called, over the duration it continues to consume noticeable amount of memory until the method returns.

What exactly happens under-the-hood during the period of the SaveChanges() call that causes this memory consumption?

1

There are 1 answers

0
Nick Patsaris On BEST ANSWER

It depends on the depth of your object graph, the deeper the graph the more memory is going to be consumed. Generally the more costly operations that happen after you call SaveChanges are the following:

  • Views are generated for the queries: Before EF can execute a query against the model, it must generate a a set of local query views to access the database. The more complex your object graph is, the more complicated the views, although they can be pre-generated to improve performance.
  • Queries are prepared: EF composes query commands, generates command trees based on metadata etc. Again, the cost rises with increased query complexity.

The cost of actually executing the queries is relatively low. See here for more info.

In general, it is recommended to use special strategies for bulk inserting with EF. See here.