Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance difference between using mmap with PROT_NONE versus PROT_READ | PROT_WRITE

Tags:

c

linux

mmap

I want to mmap a larger region of memory which I only expect to use a small portion of. The memory that is used needs read and write permissions.

Is there are difference between the following two methods for mmaping the virtual memory:

mmap(0, size, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE, (-1), 0)

and then using

mprotect(address, length, PROT_READ | PROT_WRITE) 

when I need a page

versus just mmaping the entire region with PROT_READ | PROT_WRITE permissions from the start i.e

mmap(0, size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE | MAP_NORESERVE, (-1), 0)

edit for better context into my platform:

CPU model name : Intel(R) Core(TM) i7-8565U CPU @ 1.80GHz

Kernel Version : 5.3.0-46-generic #38~18.04.1-Ubuntu SMP

like image 567
Noah Avatar asked Dec 06 '25 15:12

Noah


1 Answers

I'm not aware of any performance benefit of keeping unneeded memory as PROT_NONE, and syscalls take time, so it's almost certainly faster to allocate all of the memory with PROT_READ and PROT_WRITE the first time, rather than making extra syscalls to do that later. If you want to confirm this on your own system, then just write a benchmark that tries both ways.

like image 191
Joseph Sible-Reinstate Monica Avatar answered Dec 08 '25 05:12

Joseph Sible-Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!