AliSoftware / Dip

Simple Swift Dependency container. Use protocols to resolve your dependencies and avoid singletons / sharedInstances!
MIT License
978 stars 75 forks source link

Performance issues #178

Closed Moskacz closed 6 years ago

Moskacz commented 6 years ago

Hey,

thanks for this framework, it's very good and improves architecture of my app. However I have small performance issues when resolving components, it could take even 200ms on new device (iPhone 7). The component that I want to resolve is quite 'heavy' because it takes 4 other components as init parameters and each of this parameters has other dependencies. Is there any way that I can improve this performance?

Cheers, Michal

ilyapuchka commented 6 years ago

Hi @Moskacz . You can try improve performance by not using autowiring and containers collaboration, ensuring that you explicitly resolve components with containers where they are registered in.

Moskacz commented 6 years ago

@ilyapuchka thanks for replying, I don't use container collaboration, but I do use autowiring. What should I use instad? Let's say that I have definitions like this: container.register { URL(string:"http://myserver.com" } container.register { HttpClient(url: $0) }

then should I convert second definition to: container.register { (url: URL) in HttpClient(url: url) }

is this correct?

ilyapuchka commented 6 years ago

With this you will need to provide url as a parameter when resoling HttpClient, which is not very convenient.

let url = try container.resolve() as URL
let client = try container.resolve(arguments: url) as HttpClient

instead you can do it like this:

container.register { URL(string:"http://myserver.com" }
container.register { [unowned container] in try HttpClient(url: container.resolve()) }
let client = try container.resolve() as HttpClient

This will save some extra loops to find all the dependencies.

Moskacz commented 6 years ago

You're right. Thanks, I'll remove autowiring, and see how it performs.

Moskacz commented 6 years ago

Performance has improved by ~25%. Is there anything else I can do to improve it further?

ilyapuchka commented 6 years ago

The other thing that comes in mind that might affect performance is circular references. It might happen that some objects are created twice and then it will result in a performance hit if it's a heavy operation. You can read more here https://github.com/AliSoftware/Dip/wiki/circular-dependencies So inspect your code on that issue.

Otherwise I would suggest to profile your app and see where is the bottle neck, it might not be in DI at all.