(1) Pages acquired via anonymous mmap
can be released via munmap
, which is what glibc is doing. So for small allocations, free
returns memory to your process's heap (but retains them in the process's memory); for large allocations, free
returns memory to the system as a whole.
(2) Pages acquired via anonymous mmap
are not actually allocated until you access them the first time. At that point, the kernel has to zero them to avoid leaking information between processes. So, yes, the pages acquired by mmap
are slower to access the first time than those recycled through your process's heap. Whether you will notice the difference depends on your application.
The cost of not using mmap
is that freed memory is still tied up by your process and unavailable to other processes on the system. So this is ultimately a trade-off.
(3) It does not "force" a context switch and is, I believe, unlikely to cause one. mmap
does not actually allocate the pages; it just manipulates the page map for your process. That should typically be a non-blocking operation. (Although I admit I am not 100% sure about this.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…