malloc vs mmap in C

Peter picture Peter · Nov 16, 2009 · Viewed 41.6k times · Source

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

Answer

Jeffrey Aylesworth picture Jeffrey Aylesworth · Nov 16, 2009

mmap doesn't actually load the file into memory, so it will load faster, but editing it will be slower.

Another point is that mmap doesn't use any memory, but it takes up address space. On a 64bit machine, most of the memory address space will not have memory, so you could load up huge files, say 5GB, that you would not want to malloc.