tengo un método:¿El uso de una expresión lambda pasada a un método ralentiza una consulta de Entity Framework?
public static void GetObjects()
{
using(MyContext context = new MyContext())
{
var objects = context.Bars.Where(b => b.Prop1 != null)
.Select(b => new MyObject{Prop = b.Prop1, Name = b.Name})
.ToList();
foreach(var object in objects)
{
// do something with the object
}
}
}
I refactorizado el método para hacerlo más general, de modo que pueda pasar en un Func
para que pueda especificar la declaración where
y qué propiedad de la mesa Bars
se asigna a MyObject.Prop
de esta manera:
public static void GetObjectsV2(Func<Bar, bool> whereFunc, Func<Bar, string> selectPropFunc)
{
using(MyContext context = new MyContext())
{
var objects = context.Bars.Where(whereFunc)
.Select(b => new MyObject{Prop = selectPropFunc(b), Name = b.Name})
.ToList();
foreach(var object in objects)
{
// do something with the object
}
}
}
GetObjectsV2
parece funcionar mucho más lento que GetObjects
. ¿Hay alguna razón por la cual esto afectaría el rendimiento? De ser así, ¿hay alguna forma de evitar esto y mantener la función flexible?
Muchas gracias por la respuesta rápida! – aubreyrhodes