Why is RandomAccessFile writeLong implemented with multiple calls to write?

While profiling the application, I noticed that RandomAccessFile.writeLong took a lot of time.

I checked the code for this method and it includes eight calls to the native write method. I wrote an alternative implementation of writeLong using byte []. Something like that:

RandomAccessFile randomAccessFile = new RandomAccessFile("out.dat", "rwd");
...
byte[] aux = new byte[8];
aux[0] = (byte) ((l >>> 56) & 0xFF);
aux[1] = (byte) ((l >>> 48) & 0xFF);
aux[2] = (byte) ((l >>> 40) & 0xFF);
aux[3] = (byte) ((l >>> 32) & 0xFF);
aux[4] = (byte) ((l >>> 24) & 0xFF);
aux[5] = (byte) ((l >>> 16) & 0xFF);
aux[6] = (byte) ((l >>> 8) & 0xFF);
aux[7] = (byte) ((l >>> 0) & 0xFF);
randomAccessFile.write(aux);

I did a little test and got the following results:

Using writeLong ():
Average time to call: 91 ms

Using write (byte []):
Average call time: 11 ms

Testing on a Linux machine with Intel (R) T2300 @ 1.66 GHz

, writeLong ? , Sun, , - .

.

+5
2

( ), .

writeLong() , (JNI ). "-" , .

, Java, , - . , RandomAccessFile 1,1, 1.3 "".

RandomAccessFile: MappedByteBuffer


: JDK 1.2.2, .

+2

, RandomAccessFile.writeLong() . "rwd" "rw", , , . ( , , )

{
    RandomAccessFile raf = new RandomAccessFile("test.dat", "rwd");
    int longCount = 10000;
    long start = System.nanoTime();
    for (long l = 0; l < longCount; l++)
        raf.writeLong(l);
    long time = System.nanoTime() - start;
    System.out.printf("writeLong() took %,d us on average%n", time / longCount / 1000);
    raf.close();
}
{
    RandomAccessFile raf = new RandomAccessFile("test2.dat", "rwd");
    int longCount = 10000;
    long start = System.nanoTime();
    byte[] aux = new byte[8];
    for (long l = 0; l < longCount; l++) {
        aux[0] = (byte) (l >>> 56);
        aux[1] = (byte) (l >>> 48);
        aux[2] = (byte) (l >>> 40);
        aux[3] = (byte) (l >>> 32);
        aux[4] = (byte) (l >>> 24);
        aux[5] = (byte) (l >>> 16);
        aux[6] = (byte) (l >>> 8);
        aux[7] = (byte) l;
        raf.write(aux);
    }
    long time = System.nanoTime() - start;
    System.out.printf("write byte[8] took %,d us on average%n", time / longCount / 1000);
    raf.close();
}

writeLong() took 2,321 us on average
write byte[8] took 576 us on average

, . , 11 5400 /, 60000 /5400 = > 11 .

+2

All Articles