When to use lazy instantiation in iOS?

前端 未结 4 762
时光取名叫无心
时光取名叫无心 2020-12-12 23:05

I\'ve heard that lazy instantiation of objects in iOS is pretty common, however I\'m not exactly sure when I should use it? Could someone give a brief explanation of when I

4条回答
  •  猫巷女王i
    2020-12-12 23:29

    As with any technique, there's not a single, one-size-fits-all rule to tell you when to lazily instantiate something. I think good advice is to use lazy instantiation for things that are expensive to instantiate. If something needs to do a lot of disk or network access, or takes a lot of CPU time to set up, you're better of deferring that work until it's actually necessary (or doing it in the background). Particularly for features that a user may or may not use, there's no sense wasting a lot of time in -init (or similar) setting things up, and doing so can contribute to making your application feel sluggish to the user.

    With that said, you should avoid premature optimization. Don't spend a lot of time writing complicated code to help with performance until you've done things the obvious way, found a performance problem, and profiled your code to thoroughly understand the issue. After you've done that, you can start making changes to improve things.

提交回复
热议问题