Java,为什么从MappedByteBuffer读取比从BufferedReader读取慢

Jas*_*key 1 java io mappedbytebuffer

我尝试从可能很大的文件中读取行。

为了获得更好的性能,我尝试使用映射文件。但是当我比较性能时,我发现映射文件方式甚至比我读取的速度慢一点BufferedReader

public long chunkMappedFile(String filePath, int trunkSize) throws IOException {
    long begin = System.currentTimeMillis();
    logger.info("Processing imei file, mapped file [{}], trunk size = {} ", filePath, trunkSize);

    //Create file object
    File file = new File(filePath);

    //Get file channel in readonly mode
    FileChannel fileChannel = new RandomAccessFile(file, "r").getChannel();

    long positionStart = 0;
    StringBuilder line = new StringBuilder();
    long lineCnt = 0;
    while(positionStart < fileChannel.size()) {
        long mapSize = positionStart + trunkSize < fileChannel.size() ? trunkSize : fileChannel.size()  - positionStart ;
        MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, positionStart, mapSize);//mapped read
        for (int i = 0; i < buffer.limit(); i++) {
            char c = (char) buffer.get();
            //System.out.print(c); //Print the content of file
            if ('\n' != c) {
                line.append(c);
            } else {// line ends
                processor.processLine(line.toString());
                if (++lineCnt % 100000 ==0) {
                    try {
                        logger.info("mappedfile processed {} lines already, sleep 1ms", lineCnt);
                        Thread.sleep(1);
                    } catch (InterruptedException e) {}
                }
                line = new StringBuilder();
            }
        }
        closeDirectBuffer(buffer);
        positionStart = positionStart + buffer.limit();
    }

    long end = System.currentTimeMillis();
    logger.info("chunkMappedFile {} , trunkSize: {},  cost : {}  " ,filePath, trunkSize, end - begin);

    return lineCnt;
}

public long normalFileRead(String filePath) throws IOException {
    long begin = System.currentTimeMillis();
    logger.info("Processing imei file, Normal read file [{}] ", filePath);
    long lineCnt = 0;
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        String line;

        while ((line = br.readLine()) != null) {
            processor.processLine(line.toString());
            if (++lineCnt % 100000 ==0) {
                try {
                    logger.info("file processed {} lines already, sleep 1ms", lineCnt);
                    Thread.sleep(1);
                } catch (InterruptedException e) {}
            }            }
    }
    long end = System.currentTimeMillis();
    logger.info("normalFileRead {} ,   cost : {}  " ,filePath, end - begin);

    return lineCnt;
}
Run Code Online (Sandbox Code Playgroud)

Linux下读取537MB文件的测试结果:

MappedBuffer方式:

2017-09-28 14:33:19.277 [main] INFO  com.oppo.push.ts.dispatcher.imei2device.ImeiTransformerOfflineImpl - process imei file ends:/push/file/imei2device-local/20170928/imei2device-13 , lines :12758858 , cost :14804 , lines per seconds: 861852.0670089165
Run Code Online (Sandbox Code Playgroud)

BufferedReader方式:

2017-09-28 14:27:03.374 [main] INFO  com.oppo.push.ts.dispatcher.imei2device.ImeiTransformerOfflineImpl - process imei file ends:/push/file/imei2device-local/20170928/imei2device-13 , lines :12758858 , cost :13001 , lines per seconds: 981375.1249903854
Run Code Online (Sandbox Code Playgroud)

Gho*_*ica 5

事情就是这样:文件 IO 并不简单。

您必须记住,您的操作系统对到底要发生的事情有巨大的影响。从这个意义上说:不存在适用于所有平台上的所有 JVM 实现的可靠规则。

当您确实不得不担心最后一点性能时,在目标平台上进行深入的分析是主要的解决方案。

除此之外,你在“性能”方面的理解是错误的。含义:内存映射 IO 并不会神奇地提高应用程序中一次读取单个文件的性能。其主要优势如下:

如果您有多个进程以只读方式从同一文件访问数据(这在我编写的服务器系统中很常见),则 mmap 非常有用。mmap 允许所有这些进程共享相同的物理内存页,从而节省大量内存。

(引用自此关于使用 C系统调用的答案mmap()

换句话说:您的示例是关于读取文件内容的。最后,操作系统仍然必须转向驱动器以从那里读取所有字节。含义:它读取光盘内容并将其放入内存中。当你一次这样做时......除此之外你做一些“特殊”的事情真的并不重要。相反,当您执行“特殊”操作时,内存映射方法甚至可能会更慢,因为与“普通”读取相比会产生开销。

回到我的第一个记录:即使有 5 个进程读取同一个文件,内存映射方法也不一定更快。正如 Linux 可能会想到的那样:我已经将该文件读入内存,并且它没有改变 - 因此即使没有显式的“内存映射”,Linux 内核也可能会缓存信息。