Lack of performance when creating delegates
I have an app with a repository template. This allows me to manipulate objects via LINQ, the objects are stored in memory, so I can access them very quickly. Here's some sample code:
private Measurement ParseExact(AgentParameter agentParameter)
{
ControlledElement ce;
using (var repositoryBase = Datastore.GetRepository<ControlledElement>())
{
var mvId = Convert.ToInt32(agentParameter.ControlledParameterId);
var sId = Convert.ToInt32(agentParameter.FacilityId);
ce =
repositoryBase.Query(
t => t.FirstOrDefault(elem => elem.Sensor.Id == sId && elem.MeasuringValue.Id == mvId));
}
}
When I profiled my code with dotTrace, I found that under high load, I get a lack of performance when creating a delegate elem => elem.Sensor.Id == sId && elem.MeasuringValue.Id == mvId
. The "My Request" method looks like this:
public TOut Query<TOut>(Func<IQueryable<TEntity>, TOut> specification)
which means that I actually pass an object Func<>
every time I use it. So the question is, how can I optimize this?
source to share
You can eliminate the compilation step by explicitly tracking the state in the object, rather than using a closure.
private Measurement ParseExact(AgentParameter agentParameter)
{
ControlledElement ce;
using (var repositoryBase = Datastore.GetRepository<ControlledElement>())
{
var mvId = Convert.ToInt32(agentParameter.ControlledParameterId);
var sId = Convert.ToInt32(agentParameter.FacilityId);
var query = new ParseExactQuery(mvId, sId);
ce = repositoryBase.Query(t => t.FirstOrDefault(query.Query));
}
}
private class ParseExactQuery {
private int mvId;
private int sId;
public ParseExactQuery (int mvId, int sId) {
this.mvId = mvId;
this.sId = sId;
}
public bool Query(ControlledElement elem) {
return elem.Sensor.Id == sId && elem.MeasuringValue.Id == mvId;
}
}
source to share