I built two programs, one using malloc
and other one using mmap
. The execution time using mmap
is much less than using malloc
.
I know for example that when you're using mmap
you avoid read/writes calls to the system. And the memory access are less.
But are there any other reasons for the advantages when using mmap
over malloc
?
Thanks a lot
Almost always, memory is much faster than disk, and malloc is not what's costing time. The mmap code is faster because for your program, mmap has resulted in either less disk access, or more efficient disk access, than whatever reads and writes you compared against.
For very large requests, malloc() uses the mmap() system call to find addressable memory space. This process helps reduce the negative effects of memory fragmentation when large blocks of memory are freed but locked by smaller, more recently allocated blocks lying between them and the end of the allocated space.
In computing, mmap(2) is a POSIX-compliant Unix system call that maps files or devices into memory. It is a method of memory-mapped file I/O. It implements demand paging because file contents are not read from disk directly and initially do not use physical RAM at all.
Advantages of mmap( ) Aside from any potential page faults, reading from and writing to a memory-mapped file does not incur any system call or context switch overhead. It is as simple as accessing memory. When multiple processes map the same object into memory, the data is shared among all the processes.
Look folks, contrary to common believe, mmap is indeed a memory allocation function similar to malloc..
the mmaped file is one use of it.. you can use it as memory allocation function passing -1 as file descriptor..
so.. the common use is to use malloc for tiny objects and mmap for large ones..
this is a good strategy..
i use alloca() to for function scope only variables..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With