Search code examples
kotlinlazy-initialization

Is there any benefit of using lazy initialization as compared to Eager?


When to use lazy initialization and when Eager as even if we do lazy then the variable which we will use will still contain some data associated with the following task. So how do we choose between both? Are there any performance and memory efficient differences between the both?

Please explain any best use case as some threads are supporting eager and some lazy.


Solution

  • In general, the advantages of lazy loading are:

    • If you never need the value, you don't pay any speed or memory penalty in loading or storing it.
    • Start-up is faster.

    And the disadvantages are:

    • The first time you need the value, you have to wait while it's loaded.
    • There's often a small overhead associated with accessing the field in a thread-safe way.  (This is needed because you don't usually want two different threads doing the loading twice; and in any case you don't want any thread to see partly-loaded data.)

    In other languages another disadvantage is extra code to implement that last bit, but Kotlin's by lazy makes it ridiculously easy!

    Obviously the overall benefit depends on how likely you are to need the value at all, and the impact of a delay at start-up compared to later on.