Test Env: Linux server
SDK:
java version "1.6.0_16"
Java(TM) SE Runtime Environment (build 1.6.0_16-b01)
Java HotSpot(TM) 64-Bit Server VM (build 14.2-b01, mixed mode)
Performance output
1) file size in test: 504M
testNormalRead(): time is:4606
testMapNIO() time is:234
testDirectMem(): time is:521
MAP最快,DirectMem也差不多, Normal read 很惨。符合预期。
另外Winfdows环境下测试,跟linux不太一样,估计跟操作系统有关。
*
* Note: in test in windows via eclipse (confusion. OS arch is different)
* testNormalRead(): time is:1674
* testMapNIO() time is:187
* testDirectMem(): time is:1560
*/
NIODemoShow.java 源代码如下:
import java.util.*; import java.nio.channels.*; import java.io.*; import java.io.*; import java.nio.*; class NormalReader { public static void testNormalRead(String filename, int buffersize) throws Exception { //515M File file = new File(filename); FileInputStream in = new FileInputStream(file); byte[] buffer = new byte[buffersize]; long begin = System.currentTimeMillis(); int hasread=0; while((hasread=in.read(buffer))>0) { ; } long end = System.currentTimeMillis(); System.out.println("testNormalRead(): time is:" + (end - begin)); } } class NIODirectMemDemo{ public static void testDirectMem(String filename, int buffersize) throws Exception { //515M File file = new File(filename); FileInputStream in = new FileInputStream(file); FileChannel channel = in.getChannel(); ByteBuffer buff = ByteBuffer.allocateDirect(buffersize); long begin = System.currentTimeMillis(); while (channel.read(buff) != -1) { buff.flip(); buff.clear(); } long end = System.currentTimeMillis(); System.out.println("testDirectMem(): time is:" + (end - begin)); } } class NIODemo { public static void testMapNIO(String filename, int buffersize) throws Exception{ //file size 515M File file = new File(filename); FileInputStream in = new FileInputStream(file); FileChannel channel = in.getChannel(); /* * 内存映射文件特别适合于对大文件的操作,JAVA中的限制是最大不得超过 Integer.MAX_VALUE,即2G左右, * 不过我们可以通过分次映射文件(channel.map)的不同部分来达到操作整个文件的目的。 */ MappedByteBuffer buff = channel.map(FileChannel.MapMode.READ_ONLY, 0, file.length()); byte[] b = new byte[buffersize]; int len = (int) file.length(); long begin = System.currentTimeMillis(); for(int offset = 0; offset < len; offset += buffersize) { if (len - offset > buffersize) { buff.get(b); } else { buff.get(new byte[len - offset]); } } long end = System.currentTimeMillis(); System.out.println(" testMapNIO() time is:" + (end - begin)); return; } } public class NIODemoShow { public static void main(String[] args) throws Exception { String filename="D:\\tools\\Nero-7.8.5.0_chs.iso"; int bufsz=1024; NormalReader.testNormalRead(filename,bufsz); NIODemo.testMapNIO(filename,bufsz); NIODirectMemDemo.testDirectMem(filename,bufsz); } }