Re: Memory Management
Re: Memory Management
- Subject: Re: Memory Management
- From: publiclook <email@hidden>
- Date: Wed, 30 Jul 2003 23:15:18 -0400
On thread safe accessors:
1) A lock in necessary to make any object accessor thread safe.
2) It is generally not worth while making accessors thread safe because
such small granularity of locking is counterproductive, and when using
the accessor from within a single thread, the locks add tremendous
performance overhead for no gain.
On returning an object's instance variables from an accessor method:
1) That is what most accessors do.
2) Returning an autoreleased copy of the instance variable is sometimes
a good choice.
3) Adding an extra retain and autorelease to the returned instance
variable serves no purpose. It does not provide thread safety. It does
not allow calling code to safely make any assumptions it couldn't have
made otherwise.
4) Adding an extra retain and autorelease does add performance overhead.
My recommendation to all Cocoa programmers is that if an object is
explicitly released within a particular scope, all objects previously
obtained via an instance method of the release object within the same
scope should be explicitly retained.
Crash Example: (of something that is a bad practice anyway)
foo(NSArray *someArray)
{ // Code like this is VERY rare anyway because it isn't correct to
release
// any object in this scope that wasn't alloced, copied, or retained
in
// this scope
id someObject = [someArray lastObject];
[someArray release]; // Bogus release
NSLog(@"%@", [someObject description]);
}
Working Example: (of something that is a bad practice anyway)
foo(NSArray *someArray)
{
id someObject = [someArray lastObject];
[someObject retain];
[someArray release]; // Bogus release
NSLog(@"%@", [someObject description]);
[someObject release];
}
Now, before someone says the fact that it is a collection being
released makes any difference,
Consider the following:
foo(id something)
{
id someObject = [something giveMeAnObject];
[someObject retain];
[something release]; // Bogus release
NSLog(@"%@", [someObject description]);
[someObject release];
}
It seems this long thread has been much ado about nothing because the
cited problem is not a problem and reflects contravention of Cocoa
conventions. Furthermore, their is a natural, safe way to solve the
non-existent problem as shown above, and the solution does not add any
performance overhead to the normal and correct situations.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.