title: RandomAccessFile writeInt(int i) vs write(byte[] b) - performance
body: <p>I've faced an interesting thing today regarding <code>RandomAccessFile</code>.</p>
  
  <p>I've noticed that using <code>RandomAccessFile</code>'s <code>writeInt(int i)</code> method is much more slower than using <code>RandomAccessFile</code>'s <code>write(byte[] b)</code> where I first convert int value to byte[4] array. </p>
  
  <p>I'm doing the conversion with this code</p>
  
  <pre><code>private static byte[] intToByte(int i)
  {
     byte[] result = new byte[4];
  
     result[0] = (byte) (i &gt;&gt; 24);
     result[1] = (byte) (i &gt;&gt; 16);
     result[2] = (byte) (i &gt;&gt; 8);
     result[3] = (byte) (i);
  
    return result;
  }
  </code></pre>
  
  <p>The difference is very significant, favoring <code>write(byte[] b)</code>. </p>
  
  <p>Writing 1 million <code>int</code>s on my laptop with JDK 8:</p>
  
  <ul>
  <li>via <code>writeInt(int i)</code> method took <strong>~9 seconds</strong></li>
  <li>via <code>write(byte[] b)</code> took  <strong>~2,3 seconds</strong></li>
  </ul>
  
  <p>I have similar results in another environment, where I'm using JDK 7 and a totally different machine.</p>
  
  <p>The writeInt(int i) method delegate to native <code>write0(int b)</code> method and <code>write(byte[] b)</code> delegates to native <code>writeBytes</code>.</p>
  
  <p>When I did profiling I've noticed that the majority of the execution time was spent in <code>writeInt</code> method when it was used.</p>
  
  <p>Does anyone know why I see such a big difference? Seems like <code>writeInt</code> is way less efficient.</p>