Which of these memory management techniques is better in which situations?

The Apple Memory Management Programming Guide shows three officially sanctioned methods for writing access methods that should keep or free object references.

In the case of the first two methods (reproduced below), Apple's documentation says that "the effectiveness of Technique 2 is significantly better than Technique 1 in situations where the getter is called much more often than the setter."

// Technique 1 - (NSString*) title { return [[title retain] autorelease]; } - (void) setTitle: (NSString*) newTitle { if (title != newTitle) { [title release]; title = [newTitle retain]; // Or copy, depending on your needs. } } // Technique 2 - (NSString*) title { return title; } - (void) setTitle: (NSString*) newTitle { [title autorelease]; title = [newTitle retain]; // Or copy, depending on your needs. } 

Is this the only difference between technique 1 and technique 2, or does using one over the other have other subtle consequences that I may need to know about? And if method 2 uses a more efficient getter, does it follow that method 1 uses a more efficient getter because title gets an explicit (and presumably immediate) release?

+4
source share
2 answers

Recipient from 2 and setter from 1:

 - (NSString*) title { return title; } - (void) setTitle: (NSString*) newTitle { if (title != newTitle) { [title release]; title = [newTitle retain]; // Or copy, depending on your needs. } } 
+1
source

The second getter is fragile (it will crash if someone gains access to the title object and then frees the object), so the first is generally preferable, even if it is slower.

The first setter is more efficient and will work even in situations where the autoresource pool does not exist, so it is preferable. The reason this is more efficient is not only due to autorelease vs. release - it does no work at all if you are trying to set a property to an existing value.

0
source

Source: https://habr.com/ru/post/1334782/


All Articles