Boost Performance in .NET App

Requests from DB can be tracked or untracked. By default, all queries that return model objects from DB are trackable.

When the data context retrieves data from the database, the Entity Framework places the retrieved objects in the cache and monitors changes that occur to those objects until it uses the SaveChanges() or SaveChangesAsync() method, which commits any changes to the database. But we don’t always need to track changes. For example, we just need to display data for viewing.

To prevent the data from being cached, the AsNoTracking() method is used. When AsNoTracking() applied, the data returned from the request is not cached, that is, the request becomes untracked. This means that the Entity Framework does not perform any additional processing and does not allocate additional space for storing objects retаrieved from the database. And therefore, such queries are faster.


Now let’s get down to practice :)

Let’s say we have the following models and data context:

using Microsoft.EntityFrameworkCore;

namespace AsNoTrackinsExample
{
    public class User    
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }    
    }
    
    public class AppDbContext : DbContext    
    {
        public DbSet<User> Users { get; set; }
        protected override void  OnConfiguring(DbContextOptionsBuilder 
                                            optionsBuilder)        
        {
            optionsBuilder.UseSqlServer("yoursConnectionString");        
        }    
    }
}

And I’ve inserted in database 6828 rows for Users table.

Next step — get data from DB without AsNoTracking and with AsNoTracking and compare performance. For comparing I use Benchmark.

using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Microsoft.EntityFrameworkCore;

namespace AsNoTrackinsExample
{
    class