title: Java 18 to 30 times faster than C# when catching exceptions?
body: <p>I was just playing around with exceptions and ran two simple programs in C# and Java that randomly throw exception and count how many were caught in catch block. Although number of exceptions thrown is aproximitly the same, and the code is identical (at least to my limited knowledge) performance difference is huge? </p>
  
  <p>What takes so long in C# to catch an exception that Java doesn't do?</p>
  
  <p>Or maybe I am missing something that doesn't have anything to do with exceptions?</p>
  
  <p>Here is the code:</p>
  
  <p>Java:</p>
  
  <pre><code>Random random = new Random();
  for (int j = 0; j &lt; 10; j++) {
      int count = 0;
      long start = System.nanoTime();
      for (int i = 0; i &lt; 100000; i++) {
          try {
              if (random.nextInt(Integer.MAX_VALUE) % 2 == 0) {
                  throw new Exception();
              }
          }catch(Exception e) {
              count++;
          }
      }
      long time = System.nanoTime() - start;
      System.out.printf("%d : %.1f ms%n", count ,time / 1e6);
  }
  </code></pre>
  
  <p>C#:</p>
  
  <pre><code>Random random = new Random();
  for (int j = 0; j &lt; 10; j++)
  {
      int count = 0;
      Stopwatch sw = new Stopwatch();
      sw.Start();
      for (int i = 0; i &lt; 100000; i++)
      {
          try
          {
              if (random.Next(Int32.MaxValue) % 2 == 0)
                  throw new Exception();
          }
          catch (Exception e)
          {
              count++;
          }
      }
      sw.Stop();
      Console.WriteLine(count + ": " + sw.ElapsedMilliseconds + "ms");
  }
  </code></pre>
  
  <p>First I thought that it had something to do with modulo arithmetic, so I removed all exception catching and only left:</p>
  
  <pre><code>if (random.nextInt(Integer.MAX_VALUE) % 2 == 0) {
      count++;
  }
  </code></pre>
  
  <p>Performance was about 3ms for each inner for loop in C#, and about 1.7ms for each inner for lopp in Java.</p>
  
  <p>Now performance for both codes above:</p>
  
  <pre><code>Java                 C#
  
  50046 : 110.5 ms     49562: 1880ms
  49927 : 81.7 ms      49579: 1828ms
  50053 : 90.2 ms      49944: 1857ms
  49969 : 93.7 ms      49604: 1912ms
  50090 : 63.9 ms      49900: 1882ms
  50060 : 83.8 ms      49583: 1885ms
  49904 : 71.7 ms      49698: 1899ms
  50045 : 61.5 ms      49335: 1836ms
  49895 : 72.1 ms      49794: 1871ms
  49976 : 62.9 ms      49550: 1880ms
  </code></pre>
  
  <p>Specs if it matters:</p>
  
  <pre><code>Intel i3-2100 @ 3.10GHz
  
  java version "1.8.0_121"
  Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
  Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)
  
  C# version 6.0
  Visual Studio 2015 default compiler
  </code></pre>