Reading plist many times against creating an object and reading plist only once to access data in plist

I would like to create a data manager class that retrieves data from plist, and I wonder if I should create a class with all class methods that read plist every time the method is called and return the requested value, or create an initializer class that initializes the array ( instance variable) with plist data, and all methods are instance methods that get data from the array.

I would like to know which is more expensive: reading plist many times (e.g. 50 times) or creating an object, or just better.

Thank you for your help.

+4
source share
1 answer

This is one of the classic tradeoffs in programming - speed and memory usage. The technique of reading something once and storing it on a faster environment (in this example, in memory) is called caching. It is very popular, and not in vain. Mass storage devices are still slower than RAM, and network access is slower than local mass storage.

If you assume that the data will often be asked by the manager, and if you assume that the plist will not change (or you will not be able to detect the changes), then read the plist the first time you access the recipient, save it in iVar, and respond only with iVar, for now the layer has not changed. This uses a little more memory, but much faster for subsequent calls.

NOTE. This approach will be harmful for very large files. If you are concerned about memory usage, implement the - (void)didReceiveMemoryWarning in your view manager and clear the cache (delete it) when you have low memory.

The getter method might look like this:

 - (NSArray *)data { if (!cacheArray) { //what we do now is called "lazy initialization": we initialize our array only when we first need the data. //This is elegant, because it ensures the data will always be there when you ask for it, //but we don't need to initialize for data that might never be needed, and we automatically re-fill the array in case it has been deleted (for instance because of low memory) cacheArray = ... //read array from plist here; be sure to retain or copy it } return cacheArray; } 
+6
source

All Articles