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 int
s 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.