4
I have this method with a foreach inside
[Route("")]
[HttpGet]
[ResponseType(typeof(List<MarkupListResponse>))]
public IHttpActionResult Get(int resellerId)
{
var catalogs = _catalogService.GetAllByResellerId(resellerId).ToList();
var model = new List<MarkupListResponse>();
foreach (var catalog in catalogs)
{
model.Add(new MarkupListResponse()
{
CreatedOn = catalog.CatalogDate,
CatalogId = catalog.Id,
ItemsQuantity = catalog.Items.Count
});
}
return Ok(model);
}
In this foreach I have more than 400 items in Catalogs. As I do to pssar for a lambda, because I think it can improve the performance, I think.
I am using Entity Framework for these queries and MVC.
No, it will only make the performance worse. I already answered about, for you included: https://answall.com/a/53857/101
– Maniero
@Maniero, inside the foreach, I give one new, that is, instancio to each iteration the object Markuplistresponse and populate the properties of his. Can this interfere with performance? Because in this loop, I have a bad performance, among others in this project.
– pnet
Yes, but you can’t always escape it. In some, yes, but there is room for a deep analysis. Maybe take this
ToList()
can help but do not think much. If it is bad, the problem should be another because 400 is little thing.– Maniero
Start by optimizing your query in the database, return only the information you will use, already reflecting a
List<MarkupListResponse>
and check the indexes... It is much more likely that your bottleneck is at that point than in foreach...– Leandro Angelo
@Leandroangelo, but I got a performance just by swapping the foreach for the lambda, according to my own answer. I will do this (I followed your guidance at the bank) in another bottleneck that I have, which originated my first post on this subject, even if it has achieved improvement, but it is still very slow, for the amount of items(202)
– pnet
In what @Maniero commented, there in that post are saying that LINQ is slower than For/Foreach, but greatly improved the performance using Linq instead of foreach in my case, and now?
– pnet
You are using EF?
– Maniero
@Maniero, yes I use EF
– pnet
Then it is different, nor should have considered using otherwise, the EF will convert it to query instead of bringing it all in and processing it into memory. If you do not put this information fully relevant and necessary it becomes complicated to answer properly.
– Maniero
@Maniero, thanks. I really "ate a cap", "I stepped on the round".
– pnet