NSDocument and NSFileWrapper: strategy to reduce memory footprint?

285 views Asked by At

Based on the Apple Docs, the recommended practice for using file packages with NSDocument seems to be to keep a reference to the root NSFileWrapper in the custom NSDocument implementation.

My question: doesn't this mean that I'll end up with twice the memory footprint for my document?

Imagine a simple document with a single NSString instance variable text. Let's say the text can be quite large.

In readFromFileWrapper:… I read the NSString from the file wrapper data and store it in text. However, since the file wrapper is an instance variable, it's raw NSData is still around although all I need is the NSString version.

Is there anything that speaks against discarding the NSFileWrapper as soon as I'm done reading?

Edit: This is even more interesting when thinking about iOS and UIDocument. I have a document with potentially hundreds of images.

1

There are 1 answers

0
Wil Shipley On

This is a good question, but I’m going to answer it bluntly.

First, don’t optimize prematurely. If all you have is relatively small files, you shouldn’t worry about this yet. You should get your app working.

If, once your app works, you discover your files tend to be really large (like, hundreds of megabytes), you might think about optimizing this.

Remember, machines today very often have 8GB or more of RAM. It takes a LOT of data to fill that. Also, with virtual memory, the NSFileWrapper will map in the data files, which means they’ll inhabit memory for at least as long as they’re read, but after that they can be paged out with zero cost (they don’t need to be written back to disk, because they’re already ON disk).

Memory that is occupied but can be freed without a disk access is essentially free memory.

So, again, don’t try to optimize when you don’t have a real test case that’s actually performing poorly, because the system is already incredibly optimized, and if you optimize yourself without being able to test, you’ll as likely make things worse.