开发者

why are java RandomAccessFile so much slower than FileOutputStream?

As long as I can understand java api, opening a RandomAccessFile using "rw" does not write ervery single byte synchronously on the underlying storage device. Unlike with "rws" or "rwd".

Why is it almost the same "speed" like the unbuffered FileOutputStream with "rw" and more than 10 times slower with "rws"/"rwd"?

the following simple code shows this, and I cannot get any reasonnable explanation to this. Any clue?

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

public class StreamTest {

  public static void main(String[] args) throws Exception {

    OutputStream os;
    RandomAccessFile raf;
    int size = 10000;
    File file = new File("test.log");

    long a=System.currentTimeMillis();
    os = new FileOutputStream(file);
    for(int i=0;i<size;i++){
      os.write(("1").getBytes());
    }
    os.close();     
    long b=System.currentTimeMillis();
    System.out.println("writing direct "+(b-a));

    raf = new RandomAccessFile(file,"rws");
    for(int i=0;i<size;i++){            
      raf.write(("1").getBytes());
    }
    raf.close();

    long c=System.currentTimeMillis();
    System.out.prin开发者_C百科tln("random access write "+(c-b));

    raf = new RandomAccessFile(file,"rw");
    for(int i=0;i<size;i++){            
      raf.write(("1").getBytes());
    }
    raf.close();

    long d=System.currentTimeMillis();
    System.out.println("random access optimized write "+(d-c));
  }
}


From the docs, rws mode means:

Open for reading and writing, as with "rw", and also require that every update to the file's content or metadata be written synchronously to the underlying storage device.

It stands to reason that forcing the file's content to be written to the underlying device would be significantly slower than the other methods, which probably allow the VM/OS to cache the writes.


Appears to be system dependent: I ran your code and got:

writing direct 116
random access write 611
random access optimized write 39

OS: Linux 2.6.9

JVM:

java version "1.6.0"
Java(TM) SE Runtime Environment (build 1.6.0-b105)
Java HotSpot(TM) Server VM (build 1.6.0-b105, mixed mode)


For sake of curiosity, I changed to 100000 times and tested this code in an Android 7.1 Zebra TC20 and got these:

writing direct 2871    
random access write 99371    
random access optimized write 2426
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜