Testing queries for performance

While working within the constraints of application development, one of the things that you need to be aware of and work to avoid is performance problems with queries that hit the database. While working with Entity Framework, you have several tools which will help with this.

Getting ready

We will be using NuGet Package Manager to install the Entity Framework 4.1 assemblies.

The package installer can be found at http://www.nuget.org/.

We will also be using a database for connecting to the data and updating it.

Open the Performance Testing Queries in the included source code examples.

Execute the database setup script from the code samples included with this recipe. This can be found in the DataAccess project within the Database folder.

How to do it...

  1. First, we start by adding a test class named PerformanceTests using the following code:
    using System;
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Diagnostics;
    using System.Linq;
    using BusinessLogic;
    using DataAccess;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Test.Properties;
    namespace Test
    {
      [TestClass]
      public class PerformanceTests
      {
        private static BlogContext _context;
        [ClassInitialize]
        public static void ClassSetup(TestContext a)
        {
          Database.SetInitializer(new PerformanceTestInitializer());
          _context = new BlogContext(Settings.Default.BlogConnection);
          _context.Database.Delete();
          _context.Database.Create();
          _context.Database.Initialize(true);
        }
        [TestMethod]
        public void ShouldReturnInLessThanASecondForTenThousandRecords()
        {
          var watch = Stopwatch.StartNew();
          var items = _context.Set<Blog>();
          watch.Stop();
          Assert.IsTrue(watch.Elapsed < new TimeSpan(1000));
        }
        [TestMethod]
        public void ShouldReturnAFilteredSetInLessThan500Ticks()
        {
          var watch = Stopwatch.StartNew();
          var items = _context.Set<Blog>().Where(x=>x.Id > 500 && x.Id < 510);
          watch.Stop();
          Assert.IsTrue(watch.Elapsed < new TimeSpan(500));
        }
      }
    }
  2. Add a new C# class named PerformanceTestInitializer to the Test project using the following code:
    public class PerformanceTestInitializer : IDatabaseInitializer<BlogContext>
     {
      public void InitializeDatabase(BlogContext context)
      {
        long totalElapsed = 0;
        for (int i = 0; i < 10000; i++)
        {
          Stopwatch stopwatch = Stopwatch.StartNew();
          Blog b = new Blog {Id = i,Title = string.Format("Test {0}", i)};
          context.Blogs.Add(b);
          context.SaveChanges();
          stopwatch.Stop();
          totalElapsed += stopwatch.ElapsedTicks;
        }
        Console.WriteLine(totalElapsed / 10000);
      }
    }

How it works...

The test initialization calls a new context, and then inserts 10,000 rows of data. This is done once for the test class, and then all of the tests use that data. It is time-intensive, but can be automated for performance. This is not a unit test, but an integration test. These should not be run with every build like unit tests, but should be run at key points in the continuous build and deployment processes. Nightly builds are a great place for testing like this as it will head of costly changes late in the development cycle caused by performance.

This kind of performance testing ensures that the critical pieces of the application meet the expected level of responsiveness for our customers. The only way to elicit these kinds of requirements for us is to sit down with the customer and ask about them. How slow is unacceptable? How long does it currently take? How fast does it need to be to fit into the rhythm of your work?

There's more...

When we shop for a car, we look at the miles per gallon, the engine size, the maintenance, and all of the other performance markers. Writing software should be no different. If we run into resistance to this idea, we can use the following information for help.

Why do performance testing?

Performance testing is a tool used to avoid not meeting expectations. When we release software to a customer, there are certain expectations which come along with that process. Some of these are communicated in requirements and some are not. Most of the time the performance expectations are not communicated, but can sink the success of a project anyway. Performance testing is not about trying to squeeze every millisecond out of an application, it is about making sure that it is good enough to meet the needs of the customer.

See also

In this chapter:

  • Performing load testing against a database
  • Testing queries
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset