Note that there are some explanatory texts on larger screens.

plurals
  1. POArray Bounds Check Elimination in the CLR?
    primarykey
    data
    text
    <p>I was recently reading <a href="http://blogs.msdn.com/b/clrcodegeneration/archive/2009/08/13/array-bounds-check-elimination-in-the-clr.aspx" rel="nofollow">this article</a> by Dave Detlefs in which he presents a few cases where the CLR performs array bounds check elimination. I decided to test this myself, so I did the following:</p> <ul> <li>Opened Visual Studio 2010 Ultimate SP1</li> <li>Created a new C# project of type Console Application (targeting .NET 4 Client Profile by default)</li> <li><p>Added the following code (all sub-methods are taken directly from the article):</p> <pre><code>class Program { static void Main(string[] args) { int[] array = new int[30]; Test_SimpleAscend(array); Test_SimpleRedundant(array, 3); foreach (int i in array) { Console.WriteLine(i); } } static void Test_SimpleAscend(int[] a) { for (int i = 0; i &lt; a.Length; i++) a[i] = i; } static void Test_SimpleRedundant(int[] a, int i) { int k = a[i]; k = k + a[i]; } } </code></pre></li> <li><p>Switched to Release mode; verified that "Optimize Code" is checked in the Build options</p></li> <li>Added a breakpoint to each array access, started debugging (F5) and opened the Dissassembly window</li> </ul> <p>So here's the dissassembly for a[i] = i; in Test_SimpleAscend:</p> <pre><code> a[i] = i; 00000024 mov eax,dword ptr [ebp-4] 00000027 mov edx,dword ptr [ebp-8] 0000002a cmp eax,dword ptr [edx+4] 0000002d jb 00000034 0000002f call 64FD6E08 00000034 mov ecx,dword ptr [ebp-4] 00000037 mov dword ptr [edx+eax*4+8],ecx </code></pre> <p>The cmp/jb/call is bounds checking, actually forcing the call to be executed throws an IndexOutOfRangeException.</p> <p>Same thing for all array accesses, including the redundant access in Test_SimpleRedundant. So is there something wrong with my testing methodology, or the CLR doesn't actually eliminate bounds checking? I hope I'm wrong and if so I'd like to know how I can really get array bounds checking elimination.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload