0

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();
}
Tony
  • 618
  • 12
  • 27
kml
  • 280
  • 1
  • 2
  • 9
  • [Why not inspect the SQL generated](https://learn.microsoft.com/en-us/ef/core/miscellaneous/logging)? – Erik Philips Aug 06 '18 at 14:18
  • 2
    It has nothing to do with performance, since these are just different syntaxes - the resulting query expression tree should be one and the same. – Ivan Stoev Aug 06 '18 at 14:21

1 Answers1

2

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.

arekzyla
  • 2,878
  • 11
  • 19