Which of these calls is faster on average? I've heard that mmap
is faster for smaller allocations but I haven't heard a comparison of either. Any information on performance for these would be nice.
mmap() is usually faster than sbrk() for smaller memory allocations, or. sbrk(): sbrk increases (or decreases) the memory block assigned to the process by a given size.
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 instance, write ing the whole file actually sends all those bytes to disk.
Read uses the standard file descriptor access to files while mmap transparently maps files to locations in the process's memory. Most operating systems also use mmap every time a program gets loaded into memory for execution. Even though it is important and often used, mmap can be slow and inconsistent in its timing.
Typical implementations of malloc use brk / sbrk as the primary means of claiming memory from the OS. However, they also use mmap to get chunks for large allocations.
You should tag this with a particular implementation (like linux
) since the answer surely varies by implementation. For now I'll assume Linux since it's the most popular.
With that said, brk
is in theory more optimizable, and in practice it runs about 10% faster on my machine. Allocating one page, these are the times I get:
brk
: min 2550 cycles, typical 2650 cyclesmmap
: min 2700 cycles, typical 2800 cyclesI remember hearing something along the lines of brk
being able to skip locking the mmap
semaphore, which would explain the discrepancy.
Note: I updated these times after adjusting my test to make a dummy calls prior to timing, to ensure that the code would all be in the cache.
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