Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is EntityFramework performance affected by specifying information like primary key?

Say I have this simple entity:

public class Person
{
    public int    PersonID { get; set; }
    public string Name     { get; set; }
}

The entity framework can infer by convention that the PersonID field is the primary key. However, if I give the model builder this class:

public class PersonCfg : EntityTypeConfiguration<Person>
{
    public PersonCfg()
    {
        ToTable("Person", "Person");
        HasKey(p => p.PersonID);
    }
}

Would that improve startup performance? My thought was it might allow EF to do less reflecting and startup the app faster but I don't know how it works behind the scenes to know if it has any impact.

like image 561
user3676163 Avatar asked Nov 11 '22 07:11

user3676163


1 Answers

To test this, you can use the DbModelBuilder class to build the model yourself and track the speed of the "Compile" step.

Here's my example code (LinqPad script):

void Main()
{
    // Initialize the overall system, but don't count the result.
    BuildC();

    DateTime startDateA = DateTime.Now;
    BuildA();
    DateTime.Now.Subtract(startDateA).TotalMilliseconds.Dump("A");

    DateTime startDateB = DateTime.Now;
    BuildB();
    DateTime.Now.Subtract(startDateB).TotalMilliseconds.Dump("B");
}

public class PersonA
{
    public int PersonAId { get; set; }
    public string Name { get; set; }
}

private void BuildA()
{
    var builder = new DbModelBuilder();
    builder.Entity<PersonA>();
    var model = builder.Build(new DbProviderInfo("System.Data.SqlClient", "2008"));
    model.Compile();
}

public class PersonB
{
    public int PersonBId { get; set; }
    public string Name { get; set; }
}

private void BuildB()
{
    var builder = new DbModelBuilder();
    builder.Conventions.Remove<IdKeyDiscoveryConvention>();
    builder.Entity<PersonB>()
        .HasKey(p => p.PersonBId);
    var model = builder.Build(new DbProviderInfo("System.Data.SqlClient", "2008"));
    model.Compile();
}

public class PersonC
{
    public int PersonCId { get; set; }
    public string Name { get; set; }
}

private void BuildC()
{
    var builder = new DbModelBuilder();
    builder.Entity<PersonC>()
        .HasKey(p => p.PersonCId);
    var model = builder.Build(new DbProviderInfo("System.Data.SqlClient", "2008"));
    model.Compile();
}

I get the result of 2.0004ms to 2.0009ms. Curiously, removing conventions made the operation take longer.

like image 109
a-h Avatar answered Nov 14 '22 22:11

a-h