Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc vs mmap in C

Tags:

c

malloc

mmap

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

like image 545
Peter Avatar asked Nov 15 '09 23:11

Peter


People also ask

Is malloc faster than mmap?

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.

Does mmap call malloc?

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.

What does mmap mean in C?

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.

What are the advantages of using mmap ()?

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.


1 Answers

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..

like image 121
user410034 Avatar answered Sep 22 '22 22:09

user410034