Reputation: 323
I'm using a BindingSource with Entity Framework and when I call the
EntityContext.SaveChange();
it takes more time to execute then the next times I add New Objects to the binding source and then call the SaveChanges(); method
EDIT 2
Details:
At load form event
BindingSource.DataSource = EntityContext.Table;
The Add New Button
BindingSource.AddNew();
Table m_object= (Table)BindingSource.Current;
m_object.ID = Guid.NewGuid();
Other object data is being edited using controls bound to its properties
And then the save button
BindingSource.EndEdit();
Stopwatch sw = new Stopwatch();
sw.Start();
EntityContext.SaveChanges();
sw.Stop();
Console.WriteLine(sw.Elapsed.ToString());
If I repeated adding and saving several times,I get the following output:
00:00:01.0788243
00:00:00.0316786
00:00:00.0292763
00:00:00.0298630
00:00:00.1127312
It's notable that the first add and save operation takes almost one second more then the next times I add and save.
Upvotes: 3
Views: 601
Reputation: 67296
Also, don't forget about the EF Change Tracker that could be caching data after the first operation. Based on the MergeOption and the operation you are performing, EF might choose to not even call to the database. I would run the test with SQL Profiler on to see the difference in actual calls to the database. Also, check if the subsequent calls use the same db connection.
Upvotes: 0
Reputation: 34238
This can be for a whole lot of reasons, one possible reason is that your database is AutoGrowing when you perform your first commit. Have you got an example of the code which you are executing and the difference in times which you are observing
EDIT:
Based on your above code you are creating a new item if one doesn't exist in the database, could it be that the second time you click save you are simply performing an update operation which is quicker inside SQL? (or potentially 0 time if EF detects there are no changes)
Upvotes: 1
Reputation: 17213
Could the reason(s) that Luke provided, but also don't forget about JIT (just-in-time) compiling. When you run your C# application, it's all compiled to MSIL (Microsoft Intermediate Language) and when you start calling methods for the first time, JIT has to compile them to native code and run optimizations to fit the OS it is running on. This is a common reason why the first time you do an extensive operation there could be seconds of delay as opposed to the expected milliseconds.
Mono has the AOT (ahead-of-time) compiling capibility, which means that it skips the step and avoids that extra time the first time you call a method, but you sacrifice in performance elsewhere.
There is also a tool that allows you to pre-compile C# natively on windows, but i don't remember what it is called.
http://en.wikipedia.org/wiki/Just-in-time_compilation
Upvotes: 0