skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search