The alternative is to allocate a buffer and read data into that. Or allocate a pool of buffers and read chunks of data into those.
In terms of transferring data between a file and a buffer, the mechanism to do that varies by platform. On Apple platforms you use fcntl
to set F_NOCACHE
, but this is only effective under specific circumstances. A good rule of thumb is that everything should be page aligned, that is, the buffer, the transfer length, and the offset into the file.
As to whether memory mapping is the right tool for the job, there are specific show stoppers to watch out for:
- Is there any chance the file can go away [1]?
- Or be bigger than your available address space? [2]
- Are you streaming through the file from end to end?
If the answer to any of those is âYesâ, then Iâd stay away from memory mapping. If not, you then get to evaluate secondary criteria, profile a prototype, and so on.
Share and Enjoy
Quinn âThe Eskimo!â @ DTS @ Apple
[1] I recently discovered MAP_RESILIENT_MEDIA
, which will cause the mapping to return zeroes rather than trigger a machine exception if the file goes away. You could imagine designing a file format that took advantage of that option but, sheesh, thatâs gonna be full of pitfalls.
Oh, and this was added in macOS 10.11, just about a decade ago, so a) thereâs no worries about back deployment, and b) havenât learnt about it only recently, I clearly missed a memo (-;
[2] If youâre address space constrained you could, in theory, set up one or more windows on the file and move them around. I suspect that would really hurt performance, but I must admit to having never tried it.