Java之nio性能比较

结果:
used time:53574684
used time:1800077620
used time:12563690
可见MappedByteBuffer读写数据是最快的, 其次是FileChannel, 再其次就是RandomAccessFile.
public class BufferedCache {

/**
  * @param args
  * @throws IOException
  */
public static void main(String[] args) throws IOException {
  test3();
  test2();
  test1();
}

public static void test1() throws IOException {
  long start = System.nanoTime();
  FileChannel fc = new RandomAccessFile("/tmp/test.tmp", "rw").getChannel();
  MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, 8);

  for (int i = 0; i < 100000; i++) {
   mbb.putLong(0, i);
  }
  long end = System.nanoTime();
  System.out.println("used time:" + (end - start));
  fc.close();

}

public static void test2() throws IOException {
  long start = System.nanoTime();
  RandomAccessFile raf = new RandomAccessFile("/tmp/test.tmp", "rw");
  for (int i = 0; i < 100000; i++) {
   raf.seek(0);
   raf.writeLong(i);
  }
  long end = System.nanoTime();
  System.out.println("used time:" + (end - start));
  raf.close();
}

public static void test3() throws IOException {
  long start = System.nanoTime();
  FileChannel fc = new RandomAccessFile("/tmp/test.tmp", "rw").getChannel();
  ByteBuffer buf = ByteBuffer.allocate(8);
  for (int i = 0; i < 100000; i++) {
   buf.putLong(0, i);
   fc.write(buf, 0);
  }
  long end = System.nanoTime();
  System.out.println("used time:" + (end - start));
  fc.close();

}
}

posted @ 2016-09-07 14:19  zolo®  阅读(251)  评论(0编辑  收藏  举报