title: I wrote two pieces of code, almost exactly the same, but one runs much faster than the other (Java)
body: <p>I ran this segment of code: (outer loop runs 100 times, inner loop runs 1 billion times.)</p>
  
  <pre><code>long l = 0;
  
  for(int i = 0; i &lt; 100; i++)
      for(int j = 0; j &lt; 1000000000; j++)
          l++;
  
  System.out.println(l);
  </code></pre>
  
  <p>This took around 11-12 seconds when I ran it.</p>
  
  <p>Then I ran this segment of code:</p>
  
  <pre><code>long l = 0;
  int i = 0, j = 0;
  
  for(; i &lt; 100; i++)
      for(; j &lt; 1000000000; j++)
          l++;
  
  System.out.println(l);
  </code></pre>
  
  <p>and this took about 100 ms (0.1 seconds) whenever I ran it.</p>
  
  <p>Does anyone have any idea why there's a big difference? My theory is that for every value of 'i', the inner for loop has to initialize j again, which gives it more operations to do, so it makes sense that it takes longer. However, the difference is huge (by about 100 times), and with other similar tests, the same thing doesn't happen.</p>
  
  <p>If you want to see it yourself, this is how I timed it:</p>
  
  <pre><code>class Main {
      static long start, end;
      public static void main(String[] args) {
          start();
  
          long l = 0;
          int i = 0, j = 0;
  
          for(; i &lt; 100; i++)
              for(; j &lt; 1000000000; j++)
                  l++;
  
          System.out.println(l);
  
          end();
          print();
      }
  
      public static void start() {
          start = System.currentTimeMillis();
      }
  
      public static void end() {
          end = System.currentTimeMillis();
      }
  
      public static void print() {
          System.out.println((end -  start) + " ms.");
      }
  }
  </code></pre>