Why is dagger considered better for AWS lambda implementation than Guice?
Asked Answered
S

1

12

I know that dagger creates injection at compile time by generating code and hence its performance is better than Guice, which do it at runtime. But specifically for case of lambda, I see it mentioned at multiple places that Dagger is preferred. Is it because of the cold start problem?

Because of the cold start problem in lambda, lambda keeps doing bootstrapping multiple times whenever it receives a request after long time. So, with dagger, bootstrapping would be much faster as compared to Guice as it already has the generated code? I am saying if all the objects in Guice are also created during bootstrap as compared to Lazy loading.

Sapphire answered 2/5, 2019 at 2:5 Comment(1)
Per my suggested edit, this question is specifically about Dagger 2. Dagger 1 had the same limitations as Guice. The Dagger 2 maintainer explains when and why Dagger 2 became preferred for platforms like Android and Lambda.Ostiary
S
31

As you already know, any dependency injection framework, at some point, needs to build some sort of dependency graph of the objects that are required by your application. Building this graph is often the most computationally expensive part of the DI framework.

Guice figures it out this graph by using reflection at runtime. Dagger generates code that represents the dependency graph at compile time. I don’t know which one is faster, but I do know that using reflection incurs a non-trivial performance hit.

However, the biggest difference is that Dagger does all the heavy lifting at compile time (which means you do the work once, no matter how many times you run it), whereas Guice must do the equivalent work every time the application starts up.

Now, to answer your question, Dagger is preferred if your application frequently starts and stops. With something like an mobile app, a slower startup time mostly just degrades the UX. With Lambda, not only does it slow down the cold start time, but since you are billed for the amount of time your code is running, it’s actually going to cost you more money to be constantly rebuilding the dependency graph.

TLDR; Dagger is preferred on Lambda (for both the cold start time and the cost) because it moves the most expensive part of the DI framework to compile time instead of performing it at runtime.

Stereogram answered 4/6, 2019 at 16:54 Comment(1)
Thank you so much for this answer. It was not only very insightful but also a delight to read. Kudos!Cristencristi

© 2022 - 2024 — McMap. All rights reserved.