Home > Software engineering >  Does calling service in foreach slow down speed Asp.Net Core 3?
Does calling service in foreach slow down speed Asp.Net Core 3?

Time:09-16

I would like to ask a question. I want to use services in foreach. But I think that when I call the service to access my database for menu items, the service can open new connections. If so what can I use? After 1000 items what can it be? Can the speed of the page decrease because of this?

@foreach (var parent in Model)
{
    var menuItem = _uow.Menu.GetById(parent.Id);
    @if (menuItem != null)
    {
        <span>@menuItem.Title</span>
    }
}

The interface service

 T GetById(int id);

The Entity Framework Service

  public T GetById(int id)
    {
        return _context.Set<T>().Find(id);
    }

Thank you.

CodePudding user response:

Individually retrieving 1000 items will perform 1000 calls to the database, which is slower than a single query which will perform a single call (it's similar to performing a 1000 API calls vs a single one).

A solution to your issue would be to change your service so that you can query multiple ids at once:

var menuItems = _uow.Menu.GetByIds(Model.Select(parent => parent.Id));

and the service:

public IEnumerable<T> GetByIds(IEnumerable<int> ids)
{
    return _context.Set<T>().Where(t => ids.Contains(t.id));
}

CodePudding user response:

From your code point of view, each time you loop, you will access the database once. If there are 1000 counts of the model in the foreach, then you need to access the database 1000 times.

Assuming that it takes 0.01 seconds for the database access to return, the time consumed in the database for 1000 cycles is 10s. This is obviously unreasonable, because the time is proportional to the number of foreach.

Suggestion

If a certain kind of data needs to be accessed frequently, we generally store it in a cache, such as redis cache or MemoryCache. This can optimize speed.

  • Related