Search code examples
javafile-writingrandomaccessfile

RandomAccessFile writeInt(int i) vs write(byte[] b) - performance


I've faced an interesting thing today regarding RandomAccessFile.

I've noticed that using RandomAccessFile's writeInt(int i) method is much more slower than using RandomAccessFile's write(byte[] b) where I first convert int value to byte[4] array.

I'm doing the conversion with this code

private static byte[] intToByte(int i)
{
   byte[] result = new byte[4];

   result[0] = (byte) (i >> 24);
   result[1] = (byte) (i >> 16);
   result[2] = (byte) (i >> 8);
   result[3] = (byte) (i);

  return result;
}

The difference is very significant, favoring write(byte[] b).

Writing 1 million ints on my laptop with JDK 8:

  • via writeInt(int i) method took ~9 seconds
  • via write(byte[] b) took ~2,3 seconds

I have similar results in another environment, where I'm using JDK 7 and a totally different machine.

The writeInt(int i) method delegate to native write0(int b) method and write(byte[] b) delegates to native writeBytes.

When I did profiling I've noticed that the majority of the execution time was spent in writeInt method when it was used.

Does anyone know why I see such a big difference? Seems like writeInt is way less efficient.


Solution

  • RandomAccessFile has actually two native methods to write bytes:

    //writes an array
    private native void writeBytes(byte b[], int off, int len) throws IOException;
    

    and

    //writes one byte
    public native void write(int b) throws IOException;
    

    the method writeInt(int) writes each byte separately with the native write(int) method, while write(byte[]) uses the native writeBytes(byte[],int,int) method.

    the writeInt method does 4 method invocations to write each byte of the passed integer value, the other method uses only one invocation to write the array. Method invocations are actually expensive operations in java: for each invocation the JVM allocates additional memory for the operand stack and the local variables array.