title: C# Declaring local vs out of scope function variables and performance vs readability/robustness
body: <p>I've been wondering how to deal with this issue for some time now and I can't find an elegant solution to it. I think some examples are the easiest way to understand the problem.</p>
  
  <p>Let's say we have this code within a class and x and y need to start at 0 when their functions get called: </p>
  
  <pre><code>// here we have x as a local variable
  private void functionX() {
      int x = 0;
      // ...
      // do stuff with x
      // ...
  }
  
  // here we have y as an out of function scope variable
  int y;
  private void functionY() {
      y = 0;
      // ...
      // do stuff with y
      // ...
  }
  
  public void update() 
  {
      // this is slower because x gets a new instance every time functionX gets called    
      for (int i = 0; i &lt; 100000; i++) {
          functionX();
      }
  
      // this is faster because y gets only one instance before the function ever gets called
      for (int i = 0; i &lt; 100000; i++) {
          functionY();
      }
  }
  </code></pre>
  
  <p>I have tested this code and using the out of function scope variable instead of using the local variable yields better performance (albeit not by a lot in this example but there's a performance increase nonetheless). The downside is that you have to declare the function variable <strong>outside</strong> of function scope in order to get this performance gain which makes your code messier and more error prone.</p>
  
  <p>This is only a very simple example but what happens if you have thousands of lines of code with tons of these kind of function variables and the performance gain from having them out of function scope cannot be ignored but the mess you make from having all these variables out of scope cannot be ignored either? Is there a solution to this problem or you will just absolutely have to make a choice between performance and readability/robustness?</p>
  
  <p><strong>ps.</strong> making either x or y static variables inside their functions does not work either when you have to construct multiple objects from the class they're in (all your objects will have a single instance of x and y for the whole program runtime)</p>
  
  <p>Edit: simplified the code even more</p>