ENTERPRISE

Memory Management : Use Pointers, Speed Up Array Access

10/4/2012 3:49:28 AM

Use Pointers

Scenario/Problem:You need to directly access the memory of an object, either for efficiency or to interop with native code.
Solution:To use pointers in your code, you have to do a few things:
1.
Mark the code block as unsafe.

2.
Compile the project as unsafe using the /unsafe compiler switch (or in your project build settings).

3.
Ensure that the target runtime environment has sufficient privilege to run unsafe code (it is a security risk after all).

Here’s a simple example:

unsafe
{
    int x = 0;
    int* pX = &x;
    *pX = 13;
}

You can create pointers to any non-reference type (that also contains only non-reference types):

Point pt;
Point* pPt = &pt;
pPt->X = 13;
pPt->Y = 14;
pPt->Offset(1,2);

List<object> list = new List<object>();
//List<object>* pList = &list;//won't compile!

Entire methods and classes can be marked as unsafe:

unsafe class MyUnsafeClass {...}
unsafe void MyUnsafeMethod() {...}

Speed Up Array Access

Scenario/Problem:You want direct access to an array for performance reasons and are willing to forego .NET’s array-bounds checking and take responsibility for safe behavior yourself.
Solution:By using pointers, you can speed up array lookups by an order of magnitude, but at the price of code safety and guarantees.

This code shows that by using pointers you can gain direct access to memory, potentially overwriting data you didn’t mean to:

int size = 10;
int[] vals = new int[size];
try
{
    for (int i = 0; i < size+1; i++)
    {
        vals[i] = i;
    }
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Caught exception: " + ex.Message);
}

Console.WriteLine("Going out of bounds");
//prevent vals from moving in memory
fixed (int* pI = &vals[0])
{
    //oops, going to far--overwriting memory we don't own!
    for (int i = 0; i < size+1; i++)
    {
        pI[i] = i;
    }
    Console.WriteLine("No exception thrown! We just overwrote memory we shouldn't have!");
}

					  

You can also use pointer arithmetic, just as you would in native languages:

fixed (int* pI = &vals[0])
{
    int* pA = pI;
    while (*pA < 8)
    {
        //increment 2 * sizeof(element)
        pA += 2;

        Console.WriteLine("*pA = {0}", *pA);
    }
}

Note that adding one to a pointer does not increase the memory address by 1 byte, but by 1 increment of the data type size, which in this example is an int, or 4 bytes.

Note

Most programs do not need to use any of this pointer stuff, and it is quite dangerous to do so, as evidenced by the “unsafe” status you have to grant the code, in addition to the increased permissions required to run programs that do this. If at all possible, try to create programs that do not rely on these techniques.

Other  
  •  Memory Management : Force a Garbage Collection, Create a Cache That Still Allows Garbage Collection
  •  D-Link Cloud Router 5700 With 1750Mbps Total Band
  •  The HP Virtual Server Environment : Virtual Partitions (Peak Performance Virtualization)
  •  The HP Virtual Server Environment : nPartitions (Electrically Isolated Hardware Partitions)
  •  The HP Virtual Server Environment : The Partitioning Continuum at a Glance
  •  IBM WebSphere Process Server 7 and Enterprise Service Bus 7 : Monitoring WPS/WESB applications
  •  Microsoft Dynamics Sure Step 2010 : The Microsoft Solution Selling Process
  •  Microsoft Dynamics Sure Step 2010 : Solution selling concepts
  •  Microsoft Dynamics Sure Step 2010 : Driving value for the customer and the solution provider
  •  Active Directory Domain Services 2008 : Delegate Permissions for WMI Filters
  •  
    Most View
    OS X Mountain Lion: What’s New - The System (Part 3)
    HP Envy X2 Review - A Hybrid Tablet-Laptop Failing To Bring Up A Complete Package (Part 1)
    Linking PCs with a Network : Connecting to and Sharing Files with Other PCs on Your Network, Sharing a Printer on the Network
    How Well Do You Really Know iOS 6
    Beyond Angry Birds (Part 2)
    Play It Smart (Part 2) - Western Digital WD TV Live, Apple TV, D-Link Boxee Box
    AMD Radeon HD 7950 3GB vs. Nvidia GeForce GTX 660 Ti 2GB vs. Nvidia GeForce GTX 670 2GB (Part 3)
    Asus P8277-V Mainboard - The Key LGA 1155-Based Mainboard Line (Part 2)
    Installing or Upgrading Windows 8 : Customizing the Boot Configuration Data (part 3) - Using BCDEDIT to Customize the Startup Options
    Edifier M1380 Speakers - Can You Really Expect Better Audio Quality?
    Top 10
    Windows Server 2012 : Planning, implementing, and managing Group Policy (part 9) - Configuring WMI filtering
    Windows Server 2012 : Planning, implementing, and managing Group Policy (part 8) - Managing GPO links, Configuring security filtering
    Windows Server 2012 : Planning, implementing, and managing Group Policy (part 7) - Viewing infrastructure status, Creating GPOs
    Windows Server 2012 : Planning, implementing, and managing Group Policy (part 6) - Advanced Audit Policy Configuration
    Windows Server 2012 : Planning, implementing, and managing Group Policy (part 5) - User Rights Assignment, Security Options
    Windows Server 2012 : Planning, implementing, and managing Group Policy (part 4) - Refreshing Group Policy
    Windows Server 2012 : Planning, implementing, and managing Group Policy (part 3) - Configuring a central store, Using Starter GPOs
    Windows Server 2012 : Planning, implementing, and managing Group Policy (part 2) - Group Policy and Active Directory design
    Windows Server 2012 : Planning, implementing, and managing Group Policy (part 1) - Understanding policies vs. preferences
    Windows 8 : Monitoring, optimizing, and troubleshooting system health and performance (part 5) - Monitoring system resources by using Performance Monitor