Re: Best practices with singletons
Re: Best practices with singletons
- Subject: Re: Best practices with singletons
- From: Graham Cox <email@hidden>
- Date: Mon, 09 Jun 2014 10:12:23 +1000
On 9 Jun 2014, at 2:30 am, William Squires <email@hidden> wrote:
> uses lazy loading to instantiate the singleton the first time a reference is asked for.
Sounds good.
> Is it considered better to put all of these calls in the main() function before any other code executes,
Huh?
> or not worry about it,
Yep.
> and just access them through the above class methods when and where needed?
Exactly.
> Also, in C, it's common to throw away the return value from a function (a la printf(), which returns an int, but coders rarely use the return value), but is it good practice to throw away the result of the above method calls (messages) just to silence the compiler?
Doesn't arise in this case. If you call the [x sharedController] method, you do use the result. There's no reason to call the method and not use the result.
Point is, "lazy loading" means that the singletons are only created if and when they are actually needed. If you don't ever use one, it's never created, never takes up memory. If you go through and preinitialise them all, that's surely defeating the entire purpose of creating them lazily - may as well just have a global function that instantiates all these objects. Unless creating one of these objects takes several minutes (in which case you have other problems), then the lazy approach is the usual way to do it. Even if the very first time it's used takes a few milliseconds longer, odds are it'll never be noticed, and not matter if it is.
I have lazy loading of singletons that do a ton of work, like loading multiple nibs and setting up a complex UI. If these methods take longer the first time, which they certainly must do, it's still apparently near-instantaneous to the user. I've never bothered measuring these time periods because it's not something worth optimising - it's literally a run-once proposition.
--Graham
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden