title: What advantage is there to storing "this" in a local variable in a struct method?
body: <p>I was browsing the .NET Core source tree today and ran across <a href="https://github.com/dotnet/corefx/blob/1dc118cc46f88e4889a23190b450d89e565967fd/src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray%601.cs#L134-L143" rel="noreferrer">this pattern</a> in <code>System.Collections.Immutable.ImmutableArray&lt;T&gt;</code>:</p>
  
  <pre class="lang-cs prettyprint-override"><code>T IList&lt;T&gt;.this[int index]
  {
      get
      {
          var self = this;
          self.ThrowInvalidOperationIfNotInitialized();
          return self[index];
      }
      set { throw new NotSupportedException(); }
  }
  </code></pre>
  
  <p>This pattern (storing <code>this</code> in a local variable) seems to be consistently applied in this file whenever <code>this</code> would otherwise be referenced multiple times in the same method, but not when it is only referenced once. So I started thinking about what the relative advantages might be to doing it this way; it seems to me that the advantage is likely performance-related, so I went down this route a little further... maybe I'm overlooking something else.</p>
  
  <p>The <a href="http://en.wikipedia.org/wiki/Common_Intermediate_Language" rel="noreferrer">CIL</a> that gets emitted for the "store <code>this</code> in a local" pattern seems to look something like a <code>ldarg.0</code>, then <code>ldobj UnderlyingType</code>, then <code>stloc.0</code> so that later references come from <code>ldloc.0</code> instead of a bare <code>ldarg.0</code> like it would be to just use <code>this</code> multiple times.</p>
  
  <p>Maybe <code>ldarg.0</code> is significantly slower than <code>ldloc.0</code>, but not by enough for either the C#-to-CIL translation or the JITter to look for opportunities to optimize this for us, such that it makes more sense to write this weird-looking pattern in C# code any time we would otherwise emit two <code>ldarg.0</code> instructions in a struct instance method?</p>
  
  <p><em>Update: or, you know, I could have looked at the comments at the top of that file, which <a href="https://github.com/dotnet/corefx/blob/1dc118cc46f88e4889a23190b450d89e565967fd/src/System.Collections.Immutable/src/System/Collections/Immutable/ImmutableArray%601.cs#L18-L33" rel="noreferrer">explain</a> exactly what's going on...</em></p>