O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required