Do you only project properties you need?

Last updated by Brook Jeynes [SSW] 9 months ago.See history

When retrieving data it's much more efficient to only collect the data you need. It saves computation and IO on the database and also saves memory and CPU on the calling side.

IEnumerable<string> GetProductGuids(string category)
{
    IEnumerable<Product> products = context.Products
        .Where(x => x.Category == category)
        .ToList();
  
    return products.Select(x => x.ProductGuid);
}

Figure: Bad example - Retrieved the whole product record when we only needed 1 property

IEnumerable<string> GetProductGuids(string category)
{
    IEnumerable<string> productGuids = context.Products
        .Where(x => x.Category == category)
        .Select(x => x.ProductGuid)
        .ToList();
      
    return productGuids;
}

Figure: Good example - Retrieved only the required property.

We open source. Powered by GitHub