I've got the following:
[HttpPost]
public async Task<IEnumerable<PlotAutocompleteModel>> Get()
{
IEnumerable<PlotDomain> plots = await plotService.RetrieveAllPlots();
var concurrent = ConcurrentQueue<PlotAutoCompleteModel>();
Parallel.ForEach(plots, (plot) =>
{
concurrent.Enqueue(new PlotAutocompleteModel(plot);
});
return concurrent;
}
With this usage, it takes about two seconds. Compared to: return plots.Select(plot => new PlotsAutocompleteModel(plot)).ToList(); which takes about four and a half seconds.
But I've always been told that for a simple transformation of a domain model into a view model, a Parallel.ForEach isn't ideal, mostly because it should be for more com-putative code. Which my usage clearly doesn't do.
Clarification: Where you would use significantly more resources, for instance you have a bitmap, a large quantity, which you have to rasterize and create new images from.
Is this the proper option for this code? I clearly see a performance gain due to the raw amount of records I'm iterating then transforming. Does a better approach and exist?
Update:
public class ProductAutocompleteModel
{
private readonly PlotDomain plot;
public ProductAutocompleteModel(PlotDomain plot)
{
this.plot = plot;
}
public string ProductName => plot.Project.Name;
// Another fourteen exist.
}
PlotAutocompleteModelconstructor that is eating up time? Hopefully you're not doing any I/O in that constructor... Also, wy are you fully materializing the enumerable here anyway? ConcurrentQueue seems overkill, and even in your other example, why callToListat all? It would help if you could fill in some details to make a true MCVE, and the code here is also missing some minor syntax.