In an existing system application which I am working on, we need to decide whether we should use entity framework or stored procedure to optimize the performance of our application.
I am not a big fan of Entity Framework but still, I know some of its good features.
Entity Framework uses LINQ which provides a fantastic feature to the developers, like – compile type error checking, IntelliSense at development time, common queries across the databases etc. All these features provide quick development turnaround time.
However, I was not sure whether it provides good performance in comparison to the stored procedure or not. So, I developed a simple console application to compare the results.
I did the same operation once by using EF and the second time with a stored procedure and noted the execution time both times.
Below is my console application followed by the result.
- class Program
- {
- static void Main(string[] args)
- {
- int queries = 500;
- Stopwatch spStopwatch = new Stopwatch();
-
- spStopwatch.Start();
- for (int i = 0; i < queries; i++)
- {
- using (var sqlConn = new SqlConnection("Data Source=NJO-LPT-GJAIN;Initial Catalog=BookDb;Integrated Security=True"))
- {
- var cmd = new SqlCommand("searchBook", sqlConn) { CommandType = CommandType.StoredProcedure };
- cmd.Parameters.AddWithValue("@Bookname", "java");
- sqlConn.Open();
- SqlDataReader dr = cmd.ExecuteReader();
- List<book> books = new List<book>();
- while (dr.Read())
- {
- books.Add(new book { BookTitle = dr.GetString(0) });
- }
- sqlConn.Close();
- }
- }
- spStopwatch.Stop();
- Console.WriteLine("Time taken by SP " + spStopwatch.ElapsedMilliseconds);
-
- var context = new BookDbEntities();
- var bookset = context.Set<Book>();
- spStopwatch.Start();
- for (int i = 0; i < queries; i++)
- {
- Book books = bookset.Where(x => x.BookTitle == "java").First();
- }
- spStopwatch.Stop();
- Console.WriteLine("Time taken by EF " + spStopwatch.ElapsedMilliseconds);
- Console.ReadLine();
- }
- }
- class book
- {
- public string BookTitle;
- }
- }
I executed the same application at least 10 times and every time, the time taken by Entity Framework is almost 3-4 times more than the time taken by a stored procedure.
My opinion is that Entity Framework provides a very good feature but can’t beat the performance of the stored procedure because of its precompiled nature.
Please let me know if you have a different opinion.