Memory-mapped files and low-memory scenarios

Sedate Alien picture Sedate Alien · May 30, 2011 · Viewed 14k times · Source

How does the iOS platform handle memory-mapped files during low-memory scenarios? By low-memory scenarios, I mean when the OS sends the UIApplicationDidReceiveMemoryWarningNotification notification to all observers in the application.

Our files are mapped into memory using +[NSData dataWithContentsOfMappedFile:], the documentation for which states:

A mapped file uses virtual memory techniques to avoid copying pages of the file into memory until they are actually needed.

Does this mean that the OS will also unmap the pages when they're no longer in use? Is it possible to mark pages as being no longer in use? This data is read-only, if that changes the scenario. How about if we were to use mmap() directly? Would this be preferable?

Answer

Jeremy W. Sherman picture Jeremy W. Sherman · Jun 2, 2011

Memory-mapped files copy data from disk into memory a page at a time. Unused pages are free to be swapped out, the same as any other virtual memory, unless they have been wired into physical memory using mlock(2). Memory mapping leaves the determination of what to copy from disk to memory and when to the OS.

Dropping from the Foundation level to the BSD level to use mmap is unlikely to make much difference, beyond making code that has to interface with other Foundation code somewhat more awkward.