ORM Linq: Query or Method? Which approach is better for performance?

entity-framework entity-framework-core linq

Question

Some time ago I was on technical interview and the engineer asked me which approach is better from a performance side for example in Entity Framework. Obviously I didn't know the right answer (I said that there is no difference) and also I didn't find the solution on the internet.

tldr: Which approach is faster? Data1 or Data2?

using(MyContext db = new MyContext())
{
    var data1 = db.Users.Where(x => x.Name == "Test").FirstOrDefault();
    var data2 = (from x in db.Users where x.Name == "Test" select x).FirstOrDefault();
}

Thanks in advanced :)

1
0
8/6/2018 2:15:11 PM

Accepted Answer

Query syntax is only a syntactic sugar which is always lowered to method syntax at compile time.

Giving an example code below:

var list = new List<Entity>();

var data1 = list.Where(x => x.Name == "Test").FirstOrDefault();
var data2 = (from x in list where x.Name == "Test" select x).FirstOrDefault();

You can take a look at the lowered version of this code:

List<Entity> source = new List<Entity>();
Entity entity = source.Where(<>c.<>9__0_0 ?? (<>c.<>9__0_0 = <>c.<>9.<M>b__0_0)).FirstOrDefault();
Entity entity2 = source.Where(<>c.<>9__0_1 ?? (<>c.<>9__0_1 = <>c.<>9.<M>b__0_1)).FirstOrDefault();

As you can see the query structure for both queries is exactly the same.

Full example is here.

1
8/6/2018 6:04:56 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow