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();
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步