Muhammad Kamran

10 months ago · 3 min. reading time · ~10 ·

Blogging
>
Muhammad blog
>
Benchmark using EF Linq Queries

Benchmark using EF Linq Queries

Introduction

The benchmark is to test the performance of your code. It means using more optimized practice and avoiding any repetition of code or refining your code in a better way to improve performance.

For this purpose, we are going to use the BenchmarkDotNet Nuget package which is a lightweight, open-source, and powerful .Net library that can transform your methods into benchmarks, track those methods, and then provide insights into the performance data captured. It is easy to write BenchmarkDotNet benchmarks and the results of the benchmarking process are user-friendly as well.

Installation of BenchmarkDotNet Nuget Package

Install-Package BenchmarkDotNet

Creating A Benchmark class in .NET Core

public class ServiceManager
    {
        [Benchmark(Baseline = true)]
        public List<AuthorDTO> GetAuthors()
        {
             using var dbContext = new AppDatabaseContext();
            var authors = dbContext.Authors
                .Include(author => author.Books)
                .Select(x => new AuthorDTO
                {
                    FirstName = x.FirstName,
                    LastName = x.LastName,
                    UserName = x.UserName,
                    Email = x.Email,
                    Age = x.Age,
                    Country = x.Country,
                    AllBooks = x.Books.Select(x => new BookDTO
                    {
                        BookTitle = x.BookTitle,
                        PublishedYear = x.PublishedYear
                    }).ToList(),
                }).OrderByDescending(x => x.AllBooks.Count()).ToList();

            return authors;

        }

        [Benchmark]
        public List<AuthorDTO> OptimizedCompileQuery()
        {
            using var dbContext = new AppDatabaseContext();
            var authors = CompileQuery(dbContext).OrderByDescending(x => x.AllBooks.Count()).ToList();
            return authors;
        }

        private static readonly Func<AppDatabaseContext, IEnumerable<AuthorDTO>> CompileQuery =
            EF.CompileQuery((AppDatabaseContext context) => context.Authors.Select(x => new AuthorDTO
            {
                FirstName = x.FirstName,
                LastName = x.LastName,
                UserName = x.UserName,
                Email = x.Email,
                Age = x.Age,
                Country = x.Country,
                AllBooks = x.Books.Select(x => new BookDTO
                {
                    BookTitle = x.BookTitle,
                    PublishedYear = x.PublishedYear
                }).ToList(),

            }));
    }

In the above class, I have added two methods. The GetAuthors() method gets the author list and books a using straightforward LINQ query. The other method named OptimizedCompileQuery() uses compile query to get the authors list along with books. Once these methods are defined you can call these in your main class shown below.

static void Main(string[] args)
{
   var summary = BenchmarkRunner.Run<ServiceManager>();
}

Once you start your application you are likely to face this issue. But you can resolve it by building your application in release mode.

To resolve this you need to right-click your solution and select release from the dropdown list. When benchmarking you should always ensure that you run your project in release mode.

Sebton Bench Tet Property Fog »

Contiguratnir. Actmauies) © Meer [Aen GU v | Cortipeson Manes
+ Common Maperte Brot sortent (shack Uae propect sorfogestion to bard co deghor)
PC -
|G | priamce Cortigostin Pat am ve Oustor

or BE i Co
ety

Now, you are all set to go and test your code. Run the application and check whether you wrote an optimized code or not. Your result will look like this. shown in the below image.

eR RT Peper
STN aii Sth Fare Ba EH Ht Resi dat
ERR

(mnt ER Tr

[IA TE PH Rt re

        

 

oy
EEC

  

Ra Te
fReathipbuaton Bi BMA PETIT

   

 

RTI Rip Ae Tver testy
eT tess
[rompAtebtiagh ath arts
PPAR ap yi

 

 

   

rr

FP

 

ER RCT]

   

yo

You can see that there is almost a 100% difference between a normal LINQ query and a compiled EF Core query.

Summary

We can use benchmarks to run some tests to check the benchmark of our code as we know there is always room for improvement. The benchmark implementation is very simple and easy.

Thank you so much for reading and listening. If you found this helpful hit that clap button. Any suggestions and improvements are warmly welcome. Happy coding …..##coding #learning #selfimprovement 

Science and Technology
Comments

You may be interested in these jobs

  • Shalamar Institute of Health Sciences

    Nurse Jobs

    5 hours ago


    Shalamar Institute of Health Sciences Lahore, Pakistan Full time

    Latest Medical Staff Jobs in Lahore January 2024 has been announce through Latest advertisement Following vacancies are available in various constituent units of Shalamar Institute of Health Sciences (SIHS) which comprises Shalamar Hospital (SH), Shalamar Medical and Dental Colle ...

  • Islamabad Electric Supply Company

    IESCO Jobs

    5 hours ago


    Islamabad Electric Supply Company Islamabad, Pakistan Full time

    Islamabad Electricity Supply Company IESCO Jobs January 2024 has been announce through latest advertisement IESCO is actively looking for hiring the services of experienced, dynamic, high caliber and result oriented professionals against the following positions, who can undertake ...

  • Balochistan Police

    Junior Clerk Jobs

    5 hours ago


    Balochistan Police Quetta, Pakistan Full time

    New Balochistan Police Jobs March 2024 has been announce through latest advertisement Applications are Inviting from Suitable candidate to full these Office Staff Post ( Stenographr,Junior CLerk) and Technical Staff Post Welder,Cook Painter, All Appointment will be Done According ...