title: Declaring/initializing variables inside or outside of a double (or multiple) loop
body: <p>According to a <a href="https://stackoverflow.com/questions/8803674/declaring-variables-inside-or-outside-of-a-loop">similar question</a>, and multiple Google searches, declaring or initializing a variable outside or inside a loop "might" be the same in terms of performance. </p>
  
  <p>I am running a computer simulation, and I am trying to optimize the code as much as possible, because it has to run a lot of times and it has multiple inner loops with a lot of iterations. </p>
  
  <p>I am wondering if it worth moving all my variables outside of the loops. I have many variables that "theoretically" are constantly re-declared. I said "theoretically" because I don't know if the the Java compiler actually optimize the code and declare everything at, let's say, the method level.</p>
  
  <p>Basically, what would be more efficient? CodeA or CodeB?</p>
  
  <p>Code A:</p>
  
  <pre><code>private void codeA() {
      double a = 0.0;
  
      for (int i1 = 0; i &lt; i1_N; i1++ ) {
          // Many other loops
               for (int im = 0; i &lt; im_N; im++ ) {
                   a = 0; // a is used for the first time
                   for (int in = 0; i &lt; in_N; in++ ) {
                       a++; // calculate something with a
                   }
               }
          // close many other loops
      }
  }
  </code></pre>
  
  <p>Code B:</p>
  
  <pre><code>private void codeA() {
      double a;
  
      for (int i1 = 0; i &lt; i1_N; i1++ ) {
          // Many other loops
               for (int im = 0; i &lt; im_N; im++ ) {
                   a = 0; // a is used for the first time
                   for (int in = 0; i &lt; in_N; in++ ) {
                       a++; // calculate something with a
                   }
               }
          // close many other loops
      }
  }
  </code></pre>
  
  <p>Code C:</p>
  
  <pre><code>private void codeC() {
  
      for (int i1 = 0; i &lt; i1_N; i1++ ) {
          // Many other loops
               for (int im = 0; i &lt; im_N; im++ ) {
                   double a = 0; // a is used for the first time
                   for (int in = 0; i &lt; in_N; in++ ) {
                       a++; // calculate something with a
                   }
               }
          // close many other loops
      }
  }
  </code></pre>
  
  <p>I am just using the variable a in this example, but the computer simulation uses much more. Most of my variables are primitives (int, double, float). Does it make sense to declare primitives outside of the loop in order to improve performance? </p>