Monday, November 29, 2010

Reference and Value Types

.Net has two kinds of Types, value types and reference types, a value type is held on the thread stack, a reference type is held on the managed heap. A variable for a value type contains the fields for that instance of the type on the stack, a variable for a reference type contains a pointer to the memory location of the instance of the type on the heap. The Framework Class Library (FCL) has a large number of reference types and a small number of value types but most code will contain a higher usage of value type instances to reference type instances. A value type uses less memory (no Type object pointer, no sync block index), is faster to create (when you use a lot of them) and is not subject to, or can cause Garbage Collection.

And it's that last sentence that explains why value types are important, used properly they can improve performance, take a look at the following code example:

using System;
using System.Diagnostics;

class RefType { public Int32 x; }
struct ValueType { public Int32 x; }

public sealed class Program {
  public static void Main() {
    Int32 count = Int32.MaxValue;

    Stopwatch sw = Stopwatch.StartNew();
    for (Int32 i = 0; i < count; i++) {
      ValueType vt = new ValueType();
      vt.x = 7;
    }
    Console.WriteLine("{0} value types took     {1}", count.ToString(), sw.Elapsed.ToString());
   
    sw = Stopwatch.StartNew();
    for (Int32 i = 0; i < count; i++) {
      RefType rt = new RefType();
      rt.x = 7;
    }
    Console.WriteLine("{0} reference types took {1}", count.ToString(), sw.Elapsed.ToString());
  }
}

which produces:

2147483647 value types took     00:00:08.4344126
2147483647 reference types took 00:00:54.9586018

Instantiating lots of simple value types is much faster than instantiating lots of simple reference types - great!

No comments:

Post a Comment