9.6. 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. The user specifies the technique by selecting a radio button. To ensure accuracy in each case, the routine reads all data from the DataReader 100 times and measures the total time in ticks, which are 100-nanosecond intervals.

The C# code is shown in Example 9-10.

Example 9-10. File: DataReaderPerformanceForm.cs

// Namespaces, variables, and constants using System; using System.Configuration; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; // . . . Cursor.Current = Cursors.WaitCursor; int orderId; String customerId; int employeeId; DateTime orderDate; DateTime requiredDate; DateTime shippedDate; int shipVia; Decimal freight; String shipName; String shipAddress; String shipCity; String shipRegion; String shipPostalCode; String shipCountry; String sqlText = "SELECT OrderID, CustomerID, EmployeeID, " + "OrderDate, RequiredDate, ShippedDate, " + "ShipVia, Freight, ShipName, ShipAddress, ShipCity, " + "ShipRegion, ShipPostalCode, ShipCountry " + "FROM Orders"; // Create the connection and the command. SqlConnection conn = new SqlConnection( ...

Get ADO.NET Cookbook 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.