Search:
Locator+ Code:
FTPOnline Channels Conferences Resources Hot Topics Partner Sites Magazines About FTP RSS 2.0 Feed

Back to VSLive! Show Daily Home


Quick Code for Fast Array Access
You can access an array without having the CLR perform its index checking.
by Jeffrey Richter

VSLive! SF, Day 1, February 12, 2002 — Each time an element of an array is accessed, the CLR ensures that the index is within the array's bounds. This prevents you from accessing memory that is outside of the array, which would potentially corrupt other objects. If an invalid index is used to access an array element, the CLR throws a System.IndexOutOfRangeException exception.

As you might expect, the CLR's index checking comes at a performance cost. If you have confidence in your code and if you don't mind resorting to nonverifiable (unsafe) code, you can access an array without having the CLR perform its index checking. This C# code demonstrates this approach:

// File: UnsafeArrayAccess.cs
using System;
 
class App {
   unsafe static void Main() {

      // Construct an array consisting
of five Int32 elements. 
      Int32[] arr = new Int32[] { 1, 2, 
3, 4, 5 };

      // Obtain a pointer to the
array's 0th element.
      fixed (Int32* element = &arr[0]) 
{

         // Iterate through each
element in the array.
         // NOTE: The following code
has a bug!
         for (Int32 x = 0, n <
arr.Length; x <= n; x++) {
            Console.WriteLine(element[x]);
         }
      }
   }
}

To compile this code, enter this at the command line: csc.exe /unsafe UnsafeArrayAccess.cs. After you build this small application, running it produces these results:

1
2
3
4
5

About the Author
Jeffrey Richter is the author of Programming Applications for Microsoft Windows (Microsoft Press, 1999), and is a co-founder of Wintellect, a software education and consulting firm. He specializes in programming/design for .NET and Win32. Jeff is currently authoring the book Programming .NET Framework Applications and offers .NET technology seminars.

Back to top





Java Pro | .NET Magazine | Visual Studio Magazine | XML & Web Services Magazine
VSLive! | Thunder Lizard Events | Discussions | Newsletters | FTP Home