Why people say mmap by MappedByteBuffer is faster?

我们两清 提交于 2019-12-12 09:20:27

问题


I think mmap is not fast as using virtual memory, it still has harddisk I/O.

But many people on Internet say it's fast, but no reason.

In my test, I read a file using BufferedReader andMappedByteBuffer, the first one is faster.


回答1:


A MappedByteBuffer is suitable for reading binary files that are not read sequentially.

An example is reading a database index file containing tree data-structures with file offsets to other parts of the file. In this case, you are continually seeking forwards and backwards in the file and reading data and my tests showed that using a MappedByteBuffer was much faster than using a RandomAccessFile.

Reading a text file or binary file sequentially with a BufferedReader or BufferedInputStream is efficient. There is normally no advantage in using a memory mapped file for this and the overhead of managing the memory mapping will probably make a MappedByteBuffer slower than a BufferedReader or BufferedInputStream.




回答2:


The reason mmap is faster is the file is not all read into memory at once. The file is mapped against an address in memory, and you can access it in a non sequential way without loading the parts of the file you don't need to process.

http://en.wikipedia.org/wiki/Mmap

This is sort of application specific, but it's really meant for large files that are only partially processed and files that wouldn't normally fit into memory. There are other use cases such as shared memory and shared objects. Dynamically linked libraries are loaded using mmap so that they do not need to be loaded from the disk for every process that wants to use them. The second process to use a shared library is actually looking at the same physical memory as the first process.



来源:https://stackoverflow.com/questions/7200690/why-people-say-mmap-by-mappedbytebuffer-is-faster

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!