title: C# & .NET: stackalloc
body: <p>I have a few questions about the functionality of the <code>stackalloc</code> operator.</p>
  
  <ol>
  <li><p>How does it actually allocate? I thought it does something like:</p>
  
  <pre><code>void* stackalloc(int sizeInBytes)
  {
      void* p = StackPointer (esp);
      StackPointer += sizeInBytes;
      if(StackPointer exceeds stack size)
          throw new StackOverflowException(...);
      return p;
  }
  </code></pre>
  
  <p>But I have done a few tests, and I'm not sure that's how it work. We can't know exactly what it does and how it does it, but I want to know the basics.</p></li>
  <li><p>I thought that stack allocation (Well, I am actually <em>sure</em> about it) is faster than heap allocation. So why does this example:</p>
  
  <pre><code> class Program
   {
       static void Main(string[] args)
       {
           Stopwatch sw1 = new Stopwatch();
           sw1.Start();
           StackAllocation();
           Console.WriteLine(sw1.ElapsedTicks);
  
           Stopwatch sw2 = new Stopwatch();
           sw2.Start();
           HeapAllocation();
           Console.WriteLine(sw2.ElapsedTicks);
       }
       static unsafe void StackAllocation()
       {
           for (int i = 0; i &lt; 100; i++)
           {
               int* p = stackalloc int[100];
           }
       }
       static void HeapAllocation()
       {
           for (int i = 0; i &lt; 100; i++)
           {
               int[] a = new int[100];
           }
       }
   }
  </code></pre></li>
  </ol>
  
  <p>gives the average results of <strong>280~ ticks for stack allocation</strong>, and usually <strong>1-0 ticks for heap allocation?</strong> (On my personal computer, Intel Core i7). </p>
  
  <p>On the computer I am using now (Intel Core 2 Duo), the results make more sense that the previous ones (Probably because <em>Optimize code</em> was not checked in VS):
      <strong>460~ ticks for stack allocation</strong>, and about <strong>380 ticks for heap allocation</strong>.</p>
  
  <p>But this still doesn't make sense. Why is it so? I guess that the CLR notices that we don't use the array, so maybe it doesn't even allocate it?</p>