java 内存映射效率好高啊

来源:互联网 发布:网页游戏修改软件 编辑:程序博客网 时间:2024/06/16 14:01


package GrammarPractice;import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;public class IOTest {public static void main(String[] args) throws IOException {MappedByteBuffer mbb=new RandomAccessFile("test.txt","rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 9766*1024);long t=System.currentTimeMillis();for(int i=0;i<9766*1024;i++)mbb.get();long t2=System.currentTimeMillis();System.out.println(t2-t);t=System.currentTimeMillis();FileInputStream fis=new FileInputStream("test.txt");while(fis.read()!=-1) ;t2=System.currentTimeMillis();System.out.println(t2-t);t=System.currentTimeMillis();BufferedInputStream bis=new BufferedInputStream(new FileInputStream("test.txt"));while(bis.read()!=-1);t2=System.currentTimeMillis();System.out.println(t2-t);}}
三次运行时间分别如下,可以看到使用内存映射读取9.7M的文件只需要19ms,而BufferedInputStream要44ms,FileInputStream简直没法忍,居然要13s左右
19
12841
44

0 0
原创粉丝点击