title: Does using xor reg, reg give advantage over mov reg, 0?
body: <p>There're two well-known ways to set an integer register to zero value on x86.</p>
  
  <p>Either</p>
  
  <pre><code>mov reg, 0
  </code></pre>
  
  <p>or</p>
  
  <pre><code>xor reg, reg
  </code></pre>
  
  <p>There's an opinion that the second variant is better since the value 0 is not stored in the code and that saves several bytes of produced machine code. This is definitely good - less instruction cache is used and this can sometimes allow for faster code execution. Many compilers produce such code.</p>
  
  <p>However there's formally an inter-instruction dependency between the xor instruction and whatever earlier instruction that changes the same register. Since there's a depedency the latter instruction needs to wait until the former completes and this could reduce the processor units load and hurt performance.</p>
  
  <pre><code>add reg, 17
  ;do something else with reg here
  xor reg, reg
  </code></pre>
  
  <p>It's obvious that the result of xor will be exactly the same regardless of the initial register value. But it the processor able to recognize this?</p>
  
  <p>I tried the following test in VC++7:</p>
  
  <pre><code>const int Count = 10 * 1000 * 1000 * 1000;
  int _tmain(int argc, _TCHAR* argv[])
  {
      int i;
      DWORD start = GetTickCount();
      for( i = 0; i &lt; Count ; i++ ) {
          __asm {
              mov eax, 10
              xor eax, eax
          };
      }
      DWORD diff = GetTickCount() - start;
      start = GetTickCount();
      for( i = 0; i &lt; Count ; i++ ) {
          __asm {
              mov eax, 10
              mov eax, 0
          };
      }
      diff = GetTickCount() - start;
      return 0;
  }
  </code></pre>
  
  <p>With optimizations off both loops take exactly the same time. Does this reasonably prove that the processor recognizes that there's no dependency of <code>xor reg, reg</code> instruction on the earlier <code>mov eax, 0</code> instruction? What could be a better test to check this?</p>