Why people say mmap by MappedByteBuffer is faster?
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.
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
.
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.
精彩评论