学习了java nio原理,一直停留在理论的阶段,今天就来对java中的IO和NIO性能做个测试,测试代码主要通过堆内存、直接内存和内存映射读取一个88M的文件,测试代码如下,刚开始缓冲大小都是1KB,后面改为文件大小(88MB)。
public class IOTest
{
//读取的文件,大小为88M
static private File file = new File("D://1.pdf");
//缓冲大小1024字节
static private final int BUFFER_SIZE = 1024;
//内存映射文件
public static void MapTest() throws Exception
{
FileInputStream in = new FileInputStream(file);
FileChannel channel = in.getChannel();
//分配88M的直接内存
MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
byte[] b = new byte[1024];
int len = (int) file.length();
long begin = System.currentTimeMillis();
for (int offset = 0; offset < len; offset += 1024)
{
if (len - offset > BUFFER_SIZE)
{
buff.get(b);
}
else
{
buff.get(new byte[len - offset]);
}
}
long end = System.currentTimeMillis();
System.out.println("map time is:" + (end - begin) + "ms");
}
//直接内存
public static void DirectTest() throws Exception
{
FileInputStream in = new FileInputStream(file);
FileChannel channel = in.getChannel();
//分配1KB直接内存
ByteBuffer buff = ByteBuffer.allocateDirect(BUFFER_SIZE);
long begin = System.currentTimeMillis();
while (channel.read(buff) != -1)
{
buff.flip();
buff.clear();
}
long end = System.currentTimeMillis();
System.out.println("Direct time is:" + (end - begin) + "ms");
}
//堆内存
public static void HeapTest() throws Exception
{
FileInputStream in = new FileInputStream(file);
FileChannel channel = in.getChannel();
ByteBuffer buff = ByteBuffer.allocate(BUFFER_SIZE);//分配1KB堆内存
long begin = System.currentTimeMillis();
while (channel.read(buff) != -1)
{
buff.flip();
buff.clear();
}
long end = System.currentTimeMillis();
System.out.println("heap time is:" + (end - begin) + "ms");
}
public static void main(String[] args) throws Exception
{
MapTest();
DirectTest();
HeapTest();
}
}
程序输出结果:
内存映射文件方式:52ms
缓冲区1KB大小 缓冲区文件大小(88M)
直接内存方式: 904ms 89ms
堆内存方式: 991ms 270ms
测试结果性能显示:内存映射文件方式>直接内存方式>堆内存方式
这是因为JVM在读取数据的时候涉及到堆内存、直接内存、内核内存、磁盘。堆内存方式读取数据首先将数据从磁盘读取到内核内存,再从内核内存拷贝到直接内存,最后从直接内存拷贝到堆内存,应用程序就可以使用这些数据。内存映射文件方式和直接内存方式都是将数据保存到直接内存中,并且内存映射方式可以绕过内核内存而直接将磁盘的数据读取到直接内存中。