Ketan Ketan - 1 year ago 85
C# Question

Why is C# slower than Entity Framework 6.1.3?

I wrote some code to compare performance of C# Ado.Net and Entity Framework 6.1.3. I am calling a stored procedure which returns around 20,000 employee records and then map this data into List of "Person" objects. Then I ran 1000 iterations of this code and calculated the average time.

Here are the timings:

  • Ado Net: 638 ms

  • Entity Framework: 544 ms

To my surprise, Ado Net is around 100 ms slower than Entity Framework.

Ado.Net code:

//GetAllPersons is a stored proc hosted in Local DB instance
var adapter = new SqlDataAdapter("GetAllPersons", conn);
//Using Fast member library
var accessor = TypeAccessor.Create(typeof(Person));
MemberSet members = accessor.GetMembers();
var list = new List<Person>();
foreach(DataRow row in dt.Rows)
var person = new Person();
foreach (var member in members)
if (row[member.Name] != DBNull.Value)
accessor[person, member.Name] = row[member.Name];

Entity Framework:

var context = new AdventureWorks2012Entities1();
List<Person> list = context.GetAllPersons().ToList();

The part of the code which uses SQL Adatper to load Datatable is the one taking most of the time. I tried using SQL Datareader instead but it was even worse. Am I missing something here because supposedly plain Ado.Net should be faster than Entity Framework?

Answer Source

The Entity Framework (EF) is based on Ado.Net; see What is Entity Framework? by the Entity Framework Tutorial. Consequently, EF cannot be faster than a pure Ado.Net implementation.

However, you implemented a less ideal solution with a loop in a loop and other overhead such as using reflection. I suppose the internal EF implementation is smarter than that and possibly makes use of the context initialization instead of having an inner loop.

Try this: Have only one single employee in your table and compare the results. EF is likely to be slower.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download