Lazy Instantiation Disadvantages iOS [closed]

五迷三道 提交于 2019-12-04 21:51:40

Ok, figured I'll reword my response in the form of an answer (ad you've got too many comments now)...

In the example you've given, it's safe to use the same object instance multiple times as its internal state is unaffected. That is, it's providing a service and won't keep state between calls.

As a general rule, lazy instantiation is only really relevant to Singletons or those instances provided through a factory. For instance, like in your example, instances living for the duration of a "service" or application - such as resource handling. Usually though, you often just want to create a new object instance when you need it.

The advantages/ disadvantages of lazy initialization are:

  • You need initialize an object only once and a single instance will suffice for all service calls. State won't be held between calls. The benefit here is that the object may be time-consuming to load and so you avoid start up cost or, in a singleton context, you avoid instantiating multiple expensive objects. This also applies to memory footprint - one instance, rather than many.
  • There is a cost at run-time though if you do lazily ini an object as you've essentially delayed its construction. So, at run-time, when a user is waiting, you go and create an expensive object. Not ideal so you should avoid this - if it's a long-service object again.
  • In the example you've given, there's also a question of responsibility for memory. The client code is clearly responsible for releasing this instance. If it's a long serving object, where do they do it? Well, you may have to watch the NSApp's delegate for applicationWillTerminate.
  • If an instance maintains state that would be set between invocations of methods on an instance then this pattern can't work. The state of the instance may be inconsistent (may have been changed) between calls.

Note also that this is an instance method setting the value of an instance var if it's null... This means that, in this case, you will still have one instance per your enclosing class instance (class where this method is defined). In this context, your enclosing instance is responsible for clean up. Really, I think that this is for clarity of code, rather than memory management. Or perhaps the enclosing class is long-lived and it saves re-creating your formatter (perhaps it's more expensive to recreate than reset).

will edit if anything else comes to mind. Hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!