10.11. Improving DataReader Performance with Typed Accessors

Problem

You need to improve performance when accessing data from a DataReader.

Solution

Use DataReader typed accessors to improve performance by eliminating repeated boxing and unboxing of object data to and from .NET Framework data types.

The sample code measures the time to access data in a DataReader using three techniques: typed accessor, column ordinal, and column name. To ensure accuracy in each case, the routine reads all data from the DataReader 1,000 times and measures the total time in ticks, which are one-millisecond intervals.

The C# code in Program.cs in the project DataReaderTypedAccessors is shown in Example 10-21.

Example 10-21. File: Program.cs for DataReaderTypedAccessors solution

using System;
using System.Data;
using System.Data.SqlClient;

namespace DataReaderTypedAccessors
{
    class Program { static void Main(string[] args) { int loops = 1000; int contactID; string firstName; string middleName = null; string lastName; int startTick = 0; int elapsedTick; string sqlConnectString = "Data Source=(local);" + "Integrated security=SSPI;Initial Catalog=AdventureWorks;"; string sqlSelect = "SELECT ContactID, FirstName, MiddleName, LastName " + "FROM Person.Contact"; Console.WriteLine("---DataReader column value access timing test, " + "{0} iterations---\n", loops); SqlConnection connection = new SqlConnection(sqlConnectString); // Create the command and open the connection SqlCommand command = new SqlCommand(sqlSelect, ...

Get ADO.NET 3.5 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.