I was working on a situation this morning where, as part of a C# unit test method using Entity Framework 6 for database access, I was inserting about 1000 records into a SQL Server database.
This test was taking around 30-35 seconds to run, and I wanted to speed it up. I tried re-coding the program to do the inserts using raw SQL, and that sped things up by about a factor of 3.
Thanks to a tip I found in a StackOverflow answer by “Steve”, I was able to get the same perf increase using Entity Framework by simply disabling AutoDetectChangesEnabled:
mycontext.Configuration.AutoDetectChangesEnabled = false;
Doing that before the loop with my calls to .Add()
sped up the EF code to the point where it was performing just as well as the raw SQL.
So, in situations where you’re using EF to do lots of inserts and you don’t need AutoDetectChangesEnabled (because you’re not also doing any updates to existing records), try turning it off for a possible nice performance improvement.
More info on this from Microsoft EF team member Arthur Vickers: Secrets of DetectChanges Part 3: Switching off automatic DetectChanges
No comments:
Post a Comment
Non-spammers: Thanks for visiting! Please go ahead and leave a comment; I read them all!
Attention SPAMMERS: I review all comments before they get posted, and I REPORT 100% of spam comments to Google as spam! Why not avoid getting your account banned as quickly -- and save us both a little time -- by skipping this comment form and moving on to the next one on your list? Thanks, and I hope you have a great day!