What is lazy initialization and why is it useful?











up vote
61
down vote

favorite
24












What is lazy initialization of objects? How do you do that and what are the advantages?










share|improve this question




























    up vote
    61
    down vote

    favorite
    24












    What is lazy initialization of objects? How do you do that and what are the advantages?










    share|improve this question


























      up vote
      61
      down vote

      favorite
      24









      up vote
      61
      down vote

      favorite
      24






      24





      What is lazy initialization of objects? How do you do that and what are the advantages?










      share|improve this question















      What is lazy initialization of objects? How do you do that and what are the advantages?







      .net






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 16 '12 at 22:45







      user166390

















      asked Jun 11 '09 at 0:23









      SNA

      3,167103857




      3,167103857
























          9 Answers
          9






          active

          oldest

          votes

















          up vote
          82
          down vote













          Lazy Initialization is a performance optimization where you defer (potentially expensive) object creation until just before you actually need it.



          One good example is to not create a database connection up front, but only just before you need to get data from the database.



          The key reason for doing this is that (often) you can avoid creating the object completely if you never need it.






          share|improve this answer



















          • 32




            It should go without saying, but just in case he missed it: The reason it's an optimization is because you often find you don't need to do the creation at all, and because you might save doing some work when the computer is already busy until a time when it is less busy.
            – Joel Coehoorn
            Jun 11 '09 at 0:42










          • Good comment. I've amended the answer to incorporate your point.
            – Bevan
            Jun 11 '09 at 7:53










          • a very good (and different) use-case/reason for using Lazy is posted in the following SO question : stackoverflow.com/a/15894928/4404962 this suggestion solved exactly what we needed to solve - using Lazy as the key principal
            – lev haikin
            Mar 20 at 13:29




















          up vote
          38
          down vote













          As others have mentioned, lazy initialization is delaying initialization until a component or object is used. You can view lazy initialization as a runtime application of the YAGNI principle - "You ain't gonna need it"



          The advantages from an application perspective of lazy initialization are that users don't have to pay the initialization time for features they will not use. Suppose you were to initialize every component of your application up front. This could create a potentially long start time - users would have to wait dozens of seconds or minutes before your application is ready to use. They're waiting on and paying for initialization of features they may never use or not use right away.



          Instead, if you defer initializing those components until use time, your application will start up much quicker. The user will still have to pay the startup cost when using other components, but that cost will be amortized across the run of the program and not condensed into the beginning, and the user may associate the initialization time of these objects with the features they are using.






          share|improve this answer























          • Too bad I could give only +1! Good rationale, BTW.
            – Rajendra Uppal
            Jul 17 '11 at 4:50










          • YAGNI means "you ain't gonna need it[the feature, the code]". Lazy initialization is an optimization that is a feature in itself. I would rather say that it applies the other way around: unless you know for sure you need lazy initialization, don't use is, YAGNI.
            – Flavius
            Oct 29 at 14:45


















          up vote
          12
          down vote













          Lazy Initialization is the concept of deferring object creation until the object is actually first used. If used properly, it can result in significant performance gains.



          Personally, I've used Lazy Initialization when creating my own hand-rolled ORM in .NET 2.0. When loading my collections from the database, the actual items in the collection were lazy initialized. This meant that the collections were created quickly, but each object was loaded only when I required it.



          If you're familiar with the Singleton pattern, you've probably seen lazy initialization in action as well.



          public class SomeClassSingleton
          {
          private static SomeClass _instance = null;

          private SomeClassSingleton()
          {
          }

          public static SomeClass GetInstance()
          {
          if(_instance == null)
          _instance = new SomeClassSingleton();

          return _instance;
          }
          }


          In this case, the instance of SomeClass is not initialized until it is first needed by the SomeClassSingleton consumer.






          share|improve this answer























          • Remove the explicit private variable setting to 'null' to improve the speed slightly further ;). Anyway, it's redundant.
            – nicodemus13
            Mar 24 '11 at 15:27










          • nice point, SomeClassSingleton must be equal or lower class of SomeClass
            – Fredrick Gauss
            Jan 19 '13 at 9:39












          • what about thread safety for this singleton class?
            – Rasika Perera
            Aug 22 '14 at 18:23










          • I don't know if anyone reads old responses but i assume the private static get instance method should be public?
            – Biscuit128
            Aug 27 '14 at 8:03










          • @Biscuit128 - I do read them, and yes it should be. I updated it just in case anybody else still reads this.
            – Justin Niessner
            Aug 27 '14 at 14:25


















          up vote
          5
          down vote













          In general computing terms, 'lazy evaluation' means to defer the processing on something until you actually need it. The main idea being that you can sometimes avoid costly operations if you turn out to not need it, or if the value would change before you use it.



          A simple example of this is System.Exception.StackTrace. This is a string property on an exception, but it isn't actually built until you access it. Internally it does something like:



          String StackTrace{
          get{
          if(_stackTrace==null){
          _stackTrace = buildStackTrace();
          }
          return _stackTrace;
          }
          }


          This saves you the overhead of actually calling buildStackTrace until someone wants to see what it is.



          Properties are one way to simply provide this type of behavior.






          share|improve this answer

















          • 1




            This is not thread-safe.
            – Cristi Diaconescu
            Aug 11 '10 at 12:48






          • 2




            True, but I am not sure why you would be sharing a reference to an exception among multiple threads anyway.
            – Dolphin
            Aug 11 '10 at 15:36




















          up vote
          2
          down vote













          Here you can read about Lazy Initialization with sample code.





          • When you have an object that is
            expensive to create, and the program
            might not use it. For example, assume
            that you have in memory a Customer
            object that has an Orders property
            that contains a large array of Order
            objects that, to be initialized,
            requires a database connection. If the
            user never asks to display the Orders
            or use the data in a computation, then
            there is no reason to use system
            memory or computing cycles to create
            it. By using Lazy to declare
            the Orders object for lazy
            initialization, you can avoid wasting
            system resources when the object is
            not used.


          • When you have an object that is
            expensive to create, and you want to
            defer its creation until after other
            expensive operations have been
            completed. For example, assume that
            your program loads several object
            instances when it starts, but only
            some of them are required immediately.
            You can improve the startup
            performance of the program by
            deferring initialization of the
            objects that are not required until
            the required objects have been
            created.








          share|improve this answer




























            up vote
            2
            down vote













            Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements. These are the most common scenarios:



            When you have an object that is expensive to create, and the program might not use it. For example, assume that you have in memory a Customer object that has an Orders property that contains a large array of Order objects that, to be initialized, requires a database connection. If the user never asks to display the Orders or use the data in a computation, then there is no reason to use system memory or computing cycles to create it. By using Lazy to declare the Orders object for lazy initialization, you can avoid wasting system resources when the object is not used.



            When you have an object that is expensive to create, and you want to defer its creation until after other expensive operations have been completed. For example, assume that your program loads several object instances when it starts, but only some of them are required immediately. You can improve the startup performance of the program by deferring initialization of the objects that are not required until the required objects have been created.



            Although you can write your own code to perform lazy initialization, we recommend that you use Lazy instead. Lazy and its related types also support thread-safety and provide a consistent exception propagation policy.






            share|improve this answer




























              up vote
              2
              down vote













              //Lazy instantiation delays certain tasks. 
              //It typically improves the startup time of a C# application.

              using System;
              using System.Collections.Generic;
              using System.Linq;
              using System.Text;

              namespace LazyLoad
              {
              class Program
              {
              static void Main(string args)
              {
              Lazy<MyClass> MyLazyClass = new Lazy<MyClass>(); // create lazy class
              Console.WriteLine("IsValueCreated = {0}",MyLazyClass.IsValueCreated); // print value to check if initialization is over

              MyClass sample = MyLazyClass.Value; // real value Creation Time
              Console.WriteLine("Length = {0}", sample.Length); // print array length

              Console.WriteLine("IsValueCreated = {0}", MyLazyClass.IsValueCreated); // print value to check if initialization is over
              Console.ReadLine();
              }
              }

              class MyClass
              {
              int array;
              public MyClass()
              {
              array = new int[10];

              }

              public int Length
              {
              get
              {
              return this.array.Length;
              }
              }
              }
              }


              // out put

              // IsValueCreated = False
              // Length = 10
              // IsValueCreated = True





              share|improve this answer




























                up vote
                1
                down vote













                As what I have understood about lazy init so far, is that the program does not load/request all data a once. It waits for the use of it before requesting it from eg. a SQL-server.



                If you have a database with a large table joined with a large amount of subtables and you dont require the details joined from the other tabels unless going into "edit" or "view details", then Lazy Init. will help the application to go faster and first "lazy load" the detailsdata upon needed.



                In SQL or LINQ you can set this "setting" on your database model pr. dataelement.



                Hope this makes any sense to your question?



                A webclient (eg. a browser) does the same thing. The images are "lazy loaded" after the HTML and AJAX is also a "sort of lazy init" if used right.






                share|improve this answer




























                  up vote
                  1
                  down vote













                  The database examples that have been mentioned so far are good, but it's not restricted to just the data access layer. You could apply the same principles to any situation where performance or memory can be a concern. A good example (although not .NET) is in Cocoa, where you can wait until the user requests a window to actually load it (and its associated objects) from the nib. This can help keep memory usage down and speed up the initial application load, especially when you're talking about things like Preferences windows that won't be needed until some later time, if ever.






                  share|improve this answer





















                    Your Answer






                    StackExchange.ifUsing("editor", function () {
                    StackExchange.using("externalEditor", function () {
                    StackExchange.using("snippets", function () {
                    StackExchange.snippets.init();
                    });
                    });
                    }, "code-snippets");

                    StackExchange.ready(function() {
                    var channelOptions = {
                    tags: "".split(" "),
                    id: "1"
                    };
                    initTagRenderer("".split(" "), "".split(" "), channelOptions);

                    StackExchange.using("externalEditor", function() {
                    // Have to fire editor after snippets, if snippets enabled
                    if (StackExchange.settings.snippets.snippetsEnabled) {
                    StackExchange.using("snippets", function() {
                    createEditor();
                    });
                    }
                    else {
                    createEditor();
                    }
                    });

                    function createEditor() {
                    StackExchange.prepareEditor({
                    heartbeatType: 'answer',
                    convertImagesToLinks: true,
                    noModals: true,
                    showLowRepImageUploadWarning: true,
                    reputationToPostImages: 10,
                    bindNavPrevention: true,
                    postfix: "",
                    imageUploader: {
                    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                    allowUrls: true
                    },
                    onDemand: true,
                    discardSelector: ".discard-answer"
                    ,immediatelyShowMarkdownHelp:true
                    });


                    }
                    });














                    draft saved

                    draft discarded


















                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f978759%2fwhat-is-lazy-initialization-and-why-is-it-useful%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown

























                    9 Answers
                    9






                    active

                    oldest

                    votes








                    9 Answers
                    9






                    active

                    oldest

                    votes









                    active

                    oldest

                    votes






                    active

                    oldest

                    votes








                    up vote
                    82
                    down vote













                    Lazy Initialization is a performance optimization where you defer (potentially expensive) object creation until just before you actually need it.



                    One good example is to not create a database connection up front, but only just before you need to get data from the database.



                    The key reason for doing this is that (often) you can avoid creating the object completely if you never need it.






                    share|improve this answer



















                    • 32




                      It should go without saying, but just in case he missed it: The reason it's an optimization is because you often find you don't need to do the creation at all, and because you might save doing some work when the computer is already busy until a time when it is less busy.
                      – Joel Coehoorn
                      Jun 11 '09 at 0:42










                    • Good comment. I've amended the answer to incorporate your point.
                      – Bevan
                      Jun 11 '09 at 7:53










                    • a very good (and different) use-case/reason for using Lazy is posted in the following SO question : stackoverflow.com/a/15894928/4404962 this suggestion solved exactly what we needed to solve - using Lazy as the key principal
                      – lev haikin
                      Mar 20 at 13:29

















                    up vote
                    82
                    down vote













                    Lazy Initialization is a performance optimization where you defer (potentially expensive) object creation until just before you actually need it.



                    One good example is to not create a database connection up front, but only just before you need to get data from the database.



                    The key reason for doing this is that (often) you can avoid creating the object completely if you never need it.






                    share|improve this answer



















                    • 32




                      It should go without saying, but just in case he missed it: The reason it's an optimization is because you often find you don't need to do the creation at all, and because you might save doing some work when the computer is already busy until a time when it is less busy.
                      – Joel Coehoorn
                      Jun 11 '09 at 0:42










                    • Good comment. I've amended the answer to incorporate your point.
                      – Bevan
                      Jun 11 '09 at 7:53










                    • a very good (and different) use-case/reason for using Lazy is posted in the following SO question : stackoverflow.com/a/15894928/4404962 this suggestion solved exactly what we needed to solve - using Lazy as the key principal
                      – lev haikin
                      Mar 20 at 13:29















                    up vote
                    82
                    down vote










                    up vote
                    82
                    down vote









                    Lazy Initialization is a performance optimization where you defer (potentially expensive) object creation until just before you actually need it.



                    One good example is to not create a database connection up front, but only just before you need to get data from the database.



                    The key reason for doing this is that (often) you can avoid creating the object completely if you never need it.






                    share|improve this answer














                    Lazy Initialization is a performance optimization where you defer (potentially expensive) object creation until just before you actually need it.



                    One good example is to not create a database connection up front, but only just before you need to get data from the database.



                    The key reason for doing this is that (often) you can avoid creating the object completely if you never need it.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jun 11 '09 at 7:52

























                    answered Jun 11 '09 at 0:25









                    Bevan

                    30.6k869123




                    30.6k869123








                    • 32




                      It should go without saying, but just in case he missed it: The reason it's an optimization is because you often find you don't need to do the creation at all, and because you might save doing some work when the computer is already busy until a time when it is less busy.
                      – Joel Coehoorn
                      Jun 11 '09 at 0:42










                    • Good comment. I've amended the answer to incorporate your point.
                      – Bevan
                      Jun 11 '09 at 7:53










                    • a very good (and different) use-case/reason for using Lazy is posted in the following SO question : stackoverflow.com/a/15894928/4404962 this suggestion solved exactly what we needed to solve - using Lazy as the key principal
                      – lev haikin
                      Mar 20 at 13:29
















                    • 32




                      It should go without saying, but just in case he missed it: The reason it's an optimization is because you often find you don't need to do the creation at all, and because you might save doing some work when the computer is already busy until a time when it is less busy.
                      – Joel Coehoorn
                      Jun 11 '09 at 0:42










                    • Good comment. I've amended the answer to incorporate your point.
                      – Bevan
                      Jun 11 '09 at 7:53










                    • a very good (and different) use-case/reason for using Lazy is posted in the following SO question : stackoverflow.com/a/15894928/4404962 this suggestion solved exactly what we needed to solve - using Lazy as the key principal
                      – lev haikin
                      Mar 20 at 13:29










                    32




                    32




                    It should go without saying, but just in case he missed it: The reason it's an optimization is because you often find you don't need to do the creation at all, and because you might save doing some work when the computer is already busy until a time when it is less busy.
                    – Joel Coehoorn
                    Jun 11 '09 at 0:42




                    It should go without saying, but just in case he missed it: The reason it's an optimization is because you often find you don't need to do the creation at all, and because you might save doing some work when the computer is already busy until a time when it is less busy.
                    – Joel Coehoorn
                    Jun 11 '09 at 0:42












                    Good comment. I've amended the answer to incorporate your point.
                    – Bevan
                    Jun 11 '09 at 7:53




                    Good comment. I've amended the answer to incorporate your point.
                    – Bevan
                    Jun 11 '09 at 7:53












                    a very good (and different) use-case/reason for using Lazy is posted in the following SO question : stackoverflow.com/a/15894928/4404962 this suggestion solved exactly what we needed to solve - using Lazy as the key principal
                    – lev haikin
                    Mar 20 at 13:29






                    a very good (and different) use-case/reason for using Lazy is posted in the following SO question : stackoverflow.com/a/15894928/4404962 this suggestion solved exactly what we needed to solve - using Lazy as the key principal
                    – lev haikin
                    Mar 20 at 13:29














                    up vote
                    38
                    down vote













                    As others have mentioned, lazy initialization is delaying initialization until a component or object is used. You can view lazy initialization as a runtime application of the YAGNI principle - "You ain't gonna need it"



                    The advantages from an application perspective of lazy initialization are that users don't have to pay the initialization time for features they will not use. Suppose you were to initialize every component of your application up front. This could create a potentially long start time - users would have to wait dozens of seconds or minutes before your application is ready to use. They're waiting on and paying for initialization of features they may never use or not use right away.



                    Instead, if you defer initializing those components until use time, your application will start up much quicker. The user will still have to pay the startup cost when using other components, but that cost will be amortized across the run of the program and not condensed into the beginning, and the user may associate the initialization time of these objects with the features they are using.






                    share|improve this answer























                    • Too bad I could give only +1! Good rationale, BTW.
                      – Rajendra Uppal
                      Jul 17 '11 at 4:50










                    • YAGNI means "you ain't gonna need it[the feature, the code]". Lazy initialization is an optimization that is a feature in itself. I would rather say that it applies the other way around: unless you know for sure you need lazy initialization, don't use is, YAGNI.
                      – Flavius
                      Oct 29 at 14:45















                    up vote
                    38
                    down vote













                    As others have mentioned, lazy initialization is delaying initialization until a component or object is used. You can view lazy initialization as a runtime application of the YAGNI principle - "You ain't gonna need it"



                    The advantages from an application perspective of lazy initialization are that users don't have to pay the initialization time for features they will not use. Suppose you were to initialize every component of your application up front. This could create a potentially long start time - users would have to wait dozens of seconds or minutes before your application is ready to use. They're waiting on and paying for initialization of features they may never use or not use right away.



                    Instead, if you defer initializing those components until use time, your application will start up much quicker. The user will still have to pay the startup cost when using other components, but that cost will be amortized across the run of the program and not condensed into the beginning, and the user may associate the initialization time of these objects with the features they are using.






                    share|improve this answer























                    • Too bad I could give only +1! Good rationale, BTW.
                      – Rajendra Uppal
                      Jul 17 '11 at 4:50










                    • YAGNI means "you ain't gonna need it[the feature, the code]". Lazy initialization is an optimization that is a feature in itself. I would rather say that it applies the other way around: unless you know for sure you need lazy initialization, don't use is, YAGNI.
                      – Flavius
                      Oct 29 at 14:45













                    up vote
                    38
                    down vote










                    up vote
                    38
                    down vote









                    As others have mentioned, lazy initialization is delaying initialization until a component or object is used. You can view lazy initialization as a runtime application of the YAGNI principle - "You ain't gonna need it"



                    The advantages from an application perspective of lazy initialization are that users don't have to pay the initialization time for features they will not use. Suppose you were to initialize every component of your application up front. This could create a potentially long start time - users would have to wait dozens of seconds or minutes before your application is ready to use. They're waiting on and paying for initialization of features they may never use or not use right away.



                    Instead, if you defer initializing those components until use time, your application will start up much quicker. The user will still have to pay the startup cost when using other components, but that cost will be amortized across the run of the program and not condensed into the beginning, and the user may associate the initialization time of these objects with the features they are using.






                    share|improve this answer














                    As others have mentioned, lazy initialization is delaying initialization until a component or object is used. You can view lazy initialization as a runtime application of the YAGNI principle - "You ain't gonna need it"



                    The advantages from an application perspective of lazy initialization are that users don't have to pay the initialization time for features they will not use. Suppose you were to initialize every component of your application up front. This could create a potentially long start time - users would have to wait dozens of seconds or minutes before your application is ready to use. They're waiting on and paying for initialization of features they may never use or not use right away.



                    Instead, if you defer initializing those components until use time, your application will start up much quicker. The user will still have to pay the startup cost when using other components, but that cost will be amortized across the run of the program and not condensed into the beginning, and the user may associate the initialization time of these objects with the features they are using.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 26 at 0:33









                    RBT

                    8,44866794




                    8,44866794










                    answered Jun 11 '09 at 0:46









                    Michael

                    46.4k594127




                    46.4k594127












                    • Too bad I could give only +1! Good rationale, BTW.
                      – Rajendra Uppal
                      Jul 17 '11 at 4:50










                    • YAGNI means "you ain't gonna need it[the feature, the code]". Lazy initialization is an optimization that is a feature in itself. I would rather say that it applies the other way around: unless you know for sure you need lazy initialization, don't use is, YAGNI.
                      – Flavius
                      Oct 29 at 14:45


















                    • Too bad I could give only +1! Good rationale, BTW.
                      – Rajendra Uppal
                      Jul 17 '11 at 4:50










                    • YAGNI means "you ain't gonna need it[the feature, the code]". Lazy initialization is an optimization that is a feature in itself. I would rather say that it applies the other way around: unless you know for sure you need lazy initialization, don't use is, YAGNI.
                      – Flavius
                      Oct 29 at 14:45
















                    Too bad I could give only +1! Good rationale, BTW.
                    – Rajendra Uppal
                    Jul 17 '11 at 4:50




                    Too bad I could give only +1! Good rationale, BTW.
                    – Rajendra Uppal
                    Jul 17 '11 at 4:50












                    YAGNI means "you ain't gonna need it[the feature, the code]". Lazy initialization is an optimization that is a feature in itself. I would rather say that it applies the other way around: unless you know for sure you need lazy initialization, don't use is, YAGNI.
                    – Flavius
                    Oct 29 at 14:45




                    YAGNI means "you ain't gonna need it[the feature, the code]". Lazy initialization is an optimization that is a feature in itself. I would rather say that it applies the other way around: unless you know for sure you need lazy initialization, don't use is, YAGNI.
                    – Flavius
                    Oct 29 at 14:45










                    up vote
                    12
                    down vote













                    Lazy Initialization is the concept of deferring object creation until the object is actually first used. If used properly, it can result in significant performance gains.



                    Personally, I've used Lazy Initialization when creating my own hand-rolled ORM in .NET 2.0. When loading my collections from the database, the actual items in the collection were lazy initialized. This meant that the collections were created quickly, but each object was loaded only when I required it.



                    If you're familiar with the Singleton pattern, you've probably seen lazy initialization in action as well.



                    public class SomeClassSingleton
                    {
                    private static SomeClass _instance = null;

                    private SomeClassSingleton()
                    {
                    }

                    public static SomeClass GetInstance()
                    {
                    if(_instance == null)
                    _instance = new SomeClassSingleton();

                    return _instance;
                    }
                    }


                    In this case, the instance of SomeClass is not initialized until it is first needed by the SomeClassSingleton consumer.






                    share|improve this answer























                    • Remove the explicit private variable setting to 'null' to improve the speed slightly further ;). Anyway, it's redundant.
                      – nicodemus13
                      Mar 24 '11 at 15:27










                    • nice point, SomeClassSingleton must be equal or lower class of SomeClass
                      – Fredrick Gauss
                      Jan 19 '13 at 9:39












                    • what about thread safety for this singleton class?
                      – Rasika Perera
                      Aug 22 '14 at 18:23










                    • I don't know if anyone reads old responses but i assume the private static get instance method should be public?
                      – Biscuit128
                      Aug 27 '14 at 8:03










                    • @Biscuit128 - I do read them, and yes it should be. I updated it just in case anybody else still reads this.
                      – Justin Niessner
                      Aug 27 '14 at 14:25















                    up vote
                    12
                    down vote













                    Lazy Initialization is the concept of deferring object creation until the object is actually first used. If used properly, it can result in significant performance gains.



                    Personally, I've used Lazy Initialization when creating my own hand-rolled ORM in .NET 2.0. When loading my collections from the database, the actual items in the collection were lazy initialized. This meant that the collections were created quickly, but each object was loaded only when I required it.



                    If you're familiar with the Singleton pattern, you've probably seen lazy initialization in action as well.



                    public class SomeClassSingleton
                    {
                    private static SomeClass _instance = null;

                    private SomeClassSingleton()
                    {
                    }

                    public static SomeClass GetInstance()
                    {
                    if(_instance == null)
                    _instance = new SomeClassSingleton();

                    return _instance;
                    }
                    }


                    In this case, the instance of SomeClass is not initialized until it is first needed by the SomeClassSingleton consumer.






                    share|improve this answer























                    • Remove the explicit private variable setting to 'null' to improve the speed slightly further ;). Anyway, it's redundant.
                      – nicodemus13
                      Mar 24 '11 at 15:27










                    • nice point, SomeClassSingleton must be equal or lower class of SomeClass
                      – Fredrick Gauss
                      Jan 19 '13 at 9:39












                    • what about thread safety for this singleton class?
                      – Rasika Perera
                      Aug 22 '14 at 18:23










                    • I don't know if anyone reads old responses but i assume the private static get instance method should be public?
                      – Biscuit128
                      Aug 27 '14 at 8:03










                    • @Biscuit128 - I do read them, and yes it should be. I updated it just in case anybody else still reads this.
                      – Justin Niessner
                      Aug 27 '14 at 14:25













                    up vote
                    12
                    down vote










                    up vote
                    12
                    down vote









                    Lazy Initialization is the concept of deferring object creation until the object is actually first used. If used properly, it can result in significant performance gains.



                    Personally, I've used Lazy Initialization when creating my own hand-rolled ORM in .NET 2.0. When loading my collections from the database, the actual items in the collection were lazy initialized. This meant that the collections were created quickly, but each object was loaded only when I required it.



                    If you're familiar with the Singleton pattern, you've probably seen lazy initialization in action as well.



                    public class SomeClassSingleton
                    {
                    private static SomeClass _instance = null;

                    private SomeClassSingleton()
                    {
                    }

                    public static SomeClass GetInstance()
                    {
                    if(_instance == null)
                    _instance = new SomeClassSingleton();

                    return _instance;
                    }
                    }


                    In this case, the instance of SomeClass is not initialized until it is first needed by the SomeClassSingleton consumer.






                    share|improve this answer














                    Lazy Initialization is the concept of deferring object creation until the object is actually first used. If used properly, it can result in significant performance gains.



                    Personally, I've used Lazy Initialization when creating my own hand-rolled ORM in .NET 2.0. When loading my collections from the database, the actual items in the collection were lazy initialized. This meant that the collections were created quickly, but each object was loaded only when I required it.



                    If you're familiar with the Singleton pattern, you've probably seen lazy initialization in action as well.



                    public class SomeClassSingleton
                    {
                    private static SomeClass _instance = null;

                    private SomeClassSingleton()
                    {
                    }

                    public static SomeClass GetInstance()
                    {
                    if(_instance == null)
                    _instance = new SomeClassSingleton();

                    return _instance;
                    }
                    }


                    In this case, the instance of SomeClass is not initialized until it is first needed by the SomeClassSingleton consumer.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Aug 27 '14 at 14:25

























                    answered Jun 11 '09 at 0:41









                    Justin Niessner

                    207k30359490




                    207k30359490












                    • Remove the explicit private variable setting to 'null' to improve the speed slightly further ;). Anyway, it's redundant.
                      – nicodemus13
                      Mar 24 '11 at 15:27










                    • nice point, SomeClassSingleton must be equal or lower class of SomeClass
                      – Fredrick Gauss
                      Jan 19 '13 at 9:39












                    • what about thread safety for this singleton class?
                      – Rasika Perera
                      Aug 22 '14 at 18:23










                    • I don't know if anyone reads old responses but i assume the private static get instance method should be public?
                      – Biscuit128
                      Aug 27 '14 at 8:03










                    • @Biscuit128 - I do read them, and yes it should be. I updated it just in case anybody else still reads this.
                      – Justin Niessner
                      Aug 27 '14 at 14:25


















                    • Remove the explicit private variable setting to 'null' to improve the speed slightly further ;). Anyway, it's redundant.
                      – nicodemus13
                      Mar 24 '11 at 15:27










                    • nice point, SomeClassSingleton must be equal or lower class of SomeClass
                      – Fredrick Gauss
                      Jan 19 '13 at 9:39












                    • what about thread safety for this singleton class?
                      – Rasika Perera
                      Aug 22 '14 at 18:23










                    • I don't know if anyone reads old responses but i assume the private static get instance method should be public?
                      – Biscuit128
                      Aug 27 '14 at 8:03










                    • @Biscuit128 - I do read them, and yes it should be. I updated it just in case anybody else still reads this.
                      – Justin Niessner
                      Aug 27 '14 at 14:25
















                    Remove the explicit private variable setting to 'null' to improve the speed slightly further ;). Anyway, it's redundant.
                    – nicodemus13
                    Mar 24 '11 at 15:27




                    Remove the explicit private variable setting to 'null' to improve the speed slightly further ;). Anyway, it's redundant.
                    – nicodemus13
                    Mar 24 '11 at 15:27












                    nice point, SomeClassSingleton must be equal or lower class of SomeClass
                    – Fredrick Gauss
                    Jan 19 '13 at 9:39






                    nice point, SomeClassSingleton must be equal or lower class of SomeClass
                    – Fredrick Gauss
                    Jan 19 '13 at 9:39














                    what about thread safety for this singleton class?
                    – Rasika Perera
                    Aug 22 '14 at 18:23




                    what about thread safety for this singleton class?
                    – Rasika Perera
                    Aug 22 '14 at 18:23












                    I don't know if anyone reads old responses but i assume the private static get instance method should be public?
                    – Biscuit128
                    Aug 27 '14 at 8:03




                    I don't know if anyone reads old responses but i assume the private static get instance method should be public?
                    – Biscuit128
                    Aug 27 '14 at 8:03












                    @Biscuit128 - I do read them, and yes it should be. I updated it just in case anybody else still reads this.
                    – Justin Niessner
                    Aug 27 '14 at 14:25




                    @Biscuit128 - I do read them, and yes it should be. I updated it just in case anybody else still reads this.
                    – Justin Niessner
                    Aug 27 '14 at 14:25










                    up vote
                    5
                    down vote













                    In general computing terms, 'lazy evaluation' means to defer the processing on something until you actually need it. The main idea being that you can sometimes avoid costly operations if you turn out to not need it, or if the value would change before you use it.



                    A simple example of this is System.Exception.StackTrace. This is a string property on an exception, but it isn't actually built until you access it. Internally it does something like:



                    String StackTrace{
                    get{
                    if(_stackTrace==null){
                    _stackTrace = buildStackTrace();
                    }
                    return _stackTrace;
                    }
                    }


                    This saves you the overhead of actually calling buildStackTrace until someone wants to see what it is.



                    Properties are one way to simply provide this type of behavior.






                    share|improve this answer

















                    • 1




                      This is not thread-safe.
                      – Cristi Diaconescu
                      Aug 11 '10 at 12:48






                    • 2




                      True, but I am not sure why you would be sharing a reference to an exception among multiple threads anyway.
                      – Dolphin
                      Aug 11 '10 at 15:36

















                    up vote
                    5
                    down vote













                    In general computing terms, 'lazy evaluation' means to defer the processing on something until you actually need it. The main idea being that you can sometimes avoid costly operations if you turn out to not need it, or if the value would change before you use it.



                    A simple example of this is System.Exception.StackTrace. This is a string property on an exception, but it isn't actually built until you access it. Internally it does something like:



                    String StackTrace{
                    get{
                    if(_stackTrace==null){
                    _stackTrace = buildStackTrace();
                    }
                    return _stackTrace;
                    }
                    }


                    This saves you the overhead of actually calling buildStackTrace until someone wants to see what it is.



                    Properties are one way to simply provide this type of behavior.






                    share|improve this answer

















                    • 1




                      This is not thread-safe.
                      – Cristi Diaconescu
                      Aug 11 '10 at 12:48






                    • 2




                      True, but I am not sure why you would be sharing a reference to an exception among multiple threads anyway.
                      – Dolphin
                      Aug 11 '10 at 15:36















                    up vote
                    5
                    down vote










                    up vote
                    5
                    down vote









                    In general computing terms, 'lazy evaluation' means to defer the processing on something until you actually need it. The main idea being that you can sometimes avoid costly operations if you turn out to not need it, or if the value would change before you use it.



                    A simple example of this is System.Exception.StackTrace. This is a string property on an exception, but it isn't actually built until you access it. Internally it does something like:



                    String StackTrace{
                    get{
                    if(_stackTrace==null){
                    _stackTrace = buildStackTrace();
                    }
                    return _stackTrace;
                    }
                    }


                    This saves you the overhead of actually calling buildStackTrace until someone wants to see what it is.



                    Properties are one way to simply provide this type of behavior.






                    share|improve this answer












                    In general computing terms, 'lazy evaluation' means to defer the processing on something until you actually need it. The main idea being that you can sometimes avoid costly operations if you turn out to not need it, or if the value would change before you use it.



                    A simple example of this is System.Exception.StackTrace. This is a string property on an exception, but it isn't actually built until you access it. Internally it does something like:



                    String StackTrace{
                    get{
                    if(_stackTrace==null){
                    _stackTrace = buildStackTrace();
                    }
                    return _stackTrace;
                    }
                    }


                    This saves you the overhead of actually calling buildStackTrace until someone wants to see what it is.



                    Properties are one way to simply provide this type of behavior.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jun 11 '09 at 0:45









                    Dolphin

                    3,70612325




                    3,70612325








                    • 1




                      This is not thread-safe.
                      – Cristi Diaconescu
                      Aug 11 '10 at 12:48






                    • 2




                      True, but I am not sure why you would be sharing a reference to an exception among multiple threads anyway.
                      – Dolphin
                      Aug 11 '10 at 15:36
















                    • 1




                      This is not thread-safe.
                      – Cristi Diaconescu
                      Aug 11 '10 at 12:48






                    • 2




                      True, but I am not sure why you would be sharing a reference to an exception among multiple threads anyway.
                      – Dolphin
                      Aug 11 '10 at 15:36










                    1




                    1




                    This is not thread-safe.
                    – Cristi Diaconescu
                    Aug 11 '10 at 12:48




                    This is not thread-safe.
                    – Cristi Diaconescu
                    Aug 11 '10 at 12:48




                    2




                    2




                    True, but I am not sure why you would be sharing a reference to an exception among multiple threads anyway.
                    – Dolphin
                    Aug 11 '10 at 15:36






                    True, but I am not sure why you would be sharing a reference to an exception among multiple threads anyway.
                    – Dolphin
                    Aug 11 '10 at 15:36












                    up vote
                    2
                    down vote













                    Here you can read about Lazy Initialization with sample code.





                    • When you have an object that is
                      expensive to create, and the program
                      might not use it. For example, assume
                      that you have in memory a Customer
                      object that has an Orders property
                      that contains a large array of Order
                      objects that, to be initialized,
                      requires a database connection. If the
                      user never asks to display the Orders
                      or use the data in a computation, then
                      there is no reason to use system
                      memory or computing cycles to create
                      it. By using Lazy to declare
                      the Orders object for lazy
                      initialization, you can avoid wasting
                      system resources when the object is
                      not used.


                    • When you have an object that is
                      expensive to create, and you want to
                      defer its creation until after other
                      expensive operations have been
                      completed. For example, assume that
                      your program loads several object
                      instances when it starts, but only
                      some of them are required immediately.
                      You can improve the startup
                      performance of the program by
                      deferring initialization of the
                      objects that are not required until
                      the required objects have been
                      created.








                    share|improve this answer

























                      up vote
                      2
                      down vote













                      Here you can read about Lazy Initialization with sample code.





                      • When you have an object that is
                        expensive to create, and the program
                        might not use it. For example, assume
                        that you have in memory a Customer
                        object that has an Orders property
                        that contains a large array of Order
                        objects that, to be initialized,
                        requires a database connection. If the
                        user never asks to display the Orders
                        or use the data in a computation, then
                        there is no reason to use system
                        memory or computing cycles to create
                        it. By using Lazy to declare
                        the Orders object for lazy
                        initialization, you can avoid wasting
                        system resources when the object is
                        not used.


                      • When you have an object that is
                        expensive to create, and you want to
                        defer its creation until after other
                        expensive operations have been
                        completed. For example, assume that
                        your program loads several object
                        instances when it starts, but only
                        some of them are required immediately.
                        You can improve the startup
                        performance of the program by
                        deferring initialization of the
                        objects that are not required until
                        the required objects have been
                        created.








                      share|improve this answer























                        up vote
                        2
                        down vote










                        up vote
                        2
                        down vote









                        Here you can read about Lazy Initialization with sample code.





                        • When you have an object that is
                          expensive to create, and the program
                          might not use it. For example, assume
                          that you have in memory a Customer
                          object that has an Orders property
                          that contains a large array of Order
                          objects that, to be initialized,
                          requires a database connection. If the
                          user never asks to display the Orders
                          or use the data in a computation, then
                          there is no reason to use system
                          memory or computing cycles to create
                          it. By using Lazy to declare
                          the Orders object for lazy
                          initialization, you can avoid wasting
                          system resources when the object is
                          not used.


                        • When you have an object that is
                          expensive to create, and you want to
                          defer its creation until after other
                          expensive operations have been
                          completed. For example, assume that
                          your program loads several object
                          instances when it starts, but only
                          some of them are required immediately.
                          You can improve the startup
                          performance of the program by
                          deferring initialization of the
                          objects that are not required until
                          the required objects have been
                          created.








                        share|improve this answer












                        Here you can read about Lazy Initialization with sample code.





                        • When you have an object that is
                          expensive to create, and the program
                          might not use it. For example, assume
                          that you have in memory a Customer
                          object that has an Orders property
                          that contains a large array of Order
                          objects that, to be initialized,
                          requires a database connection. If the
                          user never asks to display the Orders
                          or use the data in a computation, then
                          there is no reason to use system
                          memory or computing cycles to create
                          it. By using Lazy to declare
                          the Orders object for lazy
                          initialization, you can avoid wasting
                          system resources when the object is
                          not used.


                        • When you have an object that is
                          expensive to create, and you want to
                          defer its creation until after other
                          expensive operations have been
                          completed. For example, assume that
                          your program loads several object
                          instances when it starts, but only
                          some of them are required immediately.
                          You can improve the startup
                          performance of the program by
                          deferring initialization of the
                          objects that are not required until
                          the required objects have been
                          created.









                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 5 '10 at 14:24









                        Amir Rezaei

                        2,13952445




                        2,13952445






















                            up vote
                            2
                            down vote













                            Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements. These are the most common scenarios:



                            When you have an object that is expensive to create, and the program might not use it. For example, assume that you have in memory a Customer object that has an Orders property that contains a large array of Order objects that, to be initialized, requires a database connection. If the user never asks to display the Orders or use the data in a computation, then there is no reason to use system memory or computing cycles to create it. By using Lazy to declare the Orders object for lazy initialization, you can avoid wasting system resources when the object is not used.



                            When you have an object that is expensive to create, and you want to defer its creation until after other expensive operations have been completed. For example, assume that your program loads several object instances when it starts, but only some of them are required immediately. You can improve the startup performance of the program by deferring initialization of the objects that are not required until the required objects have been created.



                            Although you can write your own code to perform lazy initialization, we recommend that you use Lazy instead. Lazy and its related types also support thread-safety and provide a consistent exception propagation policy.






                            share|improve this answer

























                              up vote
                              2
                              down vote













                              Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements. These are the most common scenarios:



                              When you have an object that is expensive to create, and the program might not use it. For example, assume that you have in memory a Customer object that has an Orders property that contains a large array of Order objects that, to be initialized, requires a database connection. If the user never asks to display the Orders or use the data in a computation, then there is no reason to use system memory or computing cycles to create it. By using Lazy to declare the Orders object for lazy initialization, you can avoid wasting system resources when the object is not used.



                              When you have an object that is expensive to create, and you want to defer its creation until after other expensive operations have been completed. For example, assume that your program loads several object instances when it starts, but only some of them are required immediately. You can improve the startup performance of the program by deferring initialization of the objects that are not required until the required objects have been created.



                              Although you can write your own code to perform lazy initialization, we recommend that you use Lazy instead. Lazy and its related types also support thread-safety and provide a consistent exception propagation policy.






                              share|improve this answer























                                up vote
                                2
                                down vote










                                up vote
                                2
                                down vote









                                Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements. These are the most common scenarios:



                                When you have an object that is expensive to create, and the program might not use it. For example, assume that you have in memory a Customer object that has an Orders property that contains a large array of Order objects that, to be initialized, requires a database connection. If the user never asks to display the Orders or use the data in a computation, then there is no reason to use system memory or computing cycles to create it. By using Lazy to declare the Orders object for lazy initialization, you can avoid wasting system resources when the object is not used.



                                When you have an object that is expensive to create, and you want to defer its creation until after other expensive operations have been completed. For example, assume that your program loads several object instances when it starts, but only some of them are required immediately. You can improve the startup performance of the program by deferring initialization of the objects that are not required until the required objects have been created.



                                Although you can write your own code to perform lazy initialization, we recommend that you use Lazy instead. Lazy and its related types also support thread-safety and provide a consistent exception propagation policy.






                                share|improve this answer












                                Lazy initialization of an object means that its creation is deferred until it is first used. (For this topic, the terms lazy initialization and lazy instantiation are synonymous.) Lazy initialization is primarily used to improve performance, avoid wasteful computation, and reduce program memory requirements. These are the most common scenarios:



                                When you have an object that is expensive to create, and the program might not use it. For example, assume that you have in memory a Customer object that has an Orders property that contains a large array of Order objects that, to be initialized, requires a database connection. If the user never asks to display the Orders or use the data in a computation, then there is no reason to use system memory or computing cycles to create it. By using Lazy to declare the Orders object for lazy initialization, you can avoid wasting system resources when the object is not used.



                                When you have an object that is expensive to create, and you want to defer its creation until after other expensive operations have been completed. For example, assume that your program loads several object instances when it starts, but only some of them are required immediately. You can improve the startup performance of the program by deferring initialization of the objects that are not required until the required objects have been created.



                                Although you can write your own code to perform lazy initialization, we recommend that you use Lazy instead. Lazy and its related types also support thread-safety and provide a consistent exception propagation policy.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered May 24 '11 at 13:24









                                Rakesh Kumar

                                291




                                291






















                                    up vote
                                    2
                                    down vote













                                    //Lazy instantiation delays certain tasks. 
                                    //It typically improves the startup time of a C# application.

                                    using System;
                                    using System.Collections.Generic;
                                    using System.Linq;
                                    using System.Text;

                                    namespace LazyLoad
                                    {
                                    class Program
                                    {
                                    static void Main(string args)
                                    {
                                    Lazy<MyClass> MyLazyClass = new Lazy<MyClass>(); // create lazy class
                                    Console.WriteLine("IsValueCreated = {0}",MyLazyClass.IsValueCreated); // print value to check if initialization is over

                                    MyClass sample = MyLazyClass.Value; // real value Creation Time
                                    Console.WriteLine("Length = {0}", sample.Length); // print array length

                                    Console.WriteLine("IsValueCreated = {0}", MyLazyClass.IsValueCreated); // print value to check if initialization is over
                                    Console.ReadLine();
                                    }
                                    }

                                    class MyClass
                                    {
                                    int array;
                                    public MyClass()
                                    {
                                    array = new int[10];

                                    }

                                    public int Length
                                    {
                                    get
                                    {
                                    return this.array.Length;
                                    }
                                    }
                                    }
                                    }


                                    // out put

                                    // IsValueCreated = False
                                    // Length = 10
                                    // IsValueCreated = True





                                    share|improve this answer

























                                      up vote
                                      2
                                      down vote













                                      //Lazy instantiation delays certain tasks. 
                                      //It typically improves the startup time of a C# application.

                                      using System;
                                      using System.Collections.Generic;
                                      using System.Linq;
                                      using System.Text;

                                      namespace LazyLoad
                                      {
                                      class Program
                                      {
                                      static void Main(string args)
                                      {
                                      Lazy<MyClass> MyLazyClass = new Lazy<MyClass>(); // create lazy class
                                      Console.WriteLine("IsValueCreated = {0}",MyLazyClass.IsValueCreated); // print value to check if initialization is over

                                      MyClass sample = MyLazyClass.Value; // real value Creation Time
                                      Console.WriteLine("Length = {0}", sample.Length); // print array length

                                      Console.WriteLine("IsValueCreated = {0}", MyLazyClass.IsValueCreated); // print value to check if initialization is over
                                      Console.ReadLine();
                                      }
                                      }

                                      class MyClass
                                      {
                                      int array;
                                      public MyClass()
                                      {
                                      array = new int[10];

                                      }

                                      public int Length
                                      {
                                      get
                                      {
                                      return this.array.Length;
                                      }
                                      }
                                      }
                                      }


                                      // out put

                                      // IsValueCreated = False
                                      // Length = 10
                                      // IsValueCreated = True





                                      share|improve this answer























                                        up vote
                                        2
                                        down vote










                                        up vote
                                        2
                                        down vote









                                        //Lazy instantiation delays certain tasks. 
                                        //It typically improves the startup time of a C# application.

                                        using System;
                                        using System.Collections.Generic;
                                        using System.Linq;
                                        using System.Text;

                                        namespace LazyLoad
                                        {
                                        class Program
                                        {
                                        static void Main(string args)
                                        {
                                        Lazy<MyClass> MyLazyClass = new Lazy<MyClass>(); // create lazy class
                                        Console.WriteLine("IsValueCreated = {0}",MyLazyClass.IsValueCreated); // print value to check if initialization is over

                                        MyClass sample = MyLazyClass.Value; // real value Creation Time
                                        Console.WriteLine("Length = {0}", sample.Length); // print array length

                                        Console.WriteLine("IsValueCreated = {0}", MyLazyClass.IsValueCreated); // print value to check if initialization is over
                                        Console.ReadLine();
                                        }
                                        }

                                        class MyClass
                                        {
                                        int array;
                                        public MyClass()
                                        {
                                        array = new int[10];

                                        }

                                        public int Length
                                        {
                                        get
                                        {
                                        return this.array.Length;
                                        }
                                        }
                                        }
                                        }


                                        // out put

                                        // IsValueCreated = False
                                        // Length = 10
                                        // IsValueCreated = True





                                        share|improve this answer












                                        //Lazy instantiation delays certain tasks. 
                                        //It typically improves the startup time of a C# application.

                                        using System;
                                        using System.Collections.Generic;
                                        using System.Linq;
                                        using System.Text;

                                        namespace LazyLoad
                                        {
                                        class Program
                                        {
                                        static void Main(string args)
                                        {
                                        Lazy<MyClass> MyLazyClass = new Lazy<MyClass>(); // create lazy class
                                        Console.WriteLine("IsValueCreated = {0}",MyLazyClass.IsValueCreated); // print value to check if initialization is over

                                        MyClass sample = MyLazyClass.Value; // real value Creation Time
                                        Console.WriteLine("Length = {0}", sample.Length); // print array length

                                        Console.WriteLine("IsValueCreated = {0}", MyLazyClass.IsValueCreated); // print value to check if initialization is over
                                        Console.ReadLine();
                                        }
                                        }

                                        class MyClass
                                        {
                                        int array;
                                        public MyClass()
                                        {
                                        array = new int[10];

                                        }

                                        public int Length
                                        {
                                        get
                                        {
                                        return this.array.Length;
                                        }
                                        }
                                        }
                                        }


                                        // out put

                                        // IsValueCreated = False
                                        // Length = 10
                                        // IsValueCreated = True






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Jan 5 '14 at 5:34









                                        Karthik Krishna Baiju

                                        42659




                                        42659






















                                            up vote
                                            1
                                            down vote













                                            As what I have understood about lazy init so far, is that the program does not load/request all data a once. It waits for the use of it before requesting it from eg. a SQL-server.



                                            If you have a database with a large table joined with a large amount of subtables and you dont require the details joined from the other tabels unless going into "edit" or "view details", then Lazy Init. will help the application to go faster and first "lazy load" the detailsdata upon needed.



                                            In SQL or LINQ you can set this "setting" on your database model pr. dataelement.



                                            Hope this makes any sense to your question?



                                            A webclient (eg. a browser) does the same thing. The images are "lazy loaded" after the HTML and AJAX is also a "sort of lazy init" if used right.






                                            share|improve this answer

























                                              up vote
                                              1
                                              down vote













                                              As what I have understood about lazy init so far, is that the program does not load/request all data a once. It waits for the use of it before requesting it from eg. a SQL-server.



                                              If you have a database with a large table joined with a large amount of subtables and you dont require the details joined from the other tabels unless going into "edit" or "view details", then Lazy Init. will help the application to go faster and first "lazy load" the detailsdata upon needed.



                                              In SQL or LINQ you can set this "setting" on your database model pr. dataelement.



                                              Hope this makes any sense to your question?



                                              A webclient (eg. a browser) does the same thing. The images are "lazy loaded" after the HTML and AJAX is also a "sort of lazy init" if used right.






                                              share|improve this answer























                                                up vote
                                                1
                                                down vote










                                                up vote
                                                1
                                                down vote









                                                As what I have understood about lazy init so far, is that the program does not load/request all data a once. It waits for the use of it before requesting it from eg. a SQL-server.



                                                If you have a database with a large table joined with a large amount of subtables and you dont require the details joined from the other tabels unless going into "edit" or "view details", then Lazy Init. will help the application to go faster and first "lazy load" the detailsdata upon needed.



                                                In SQL or LINQ you can set this "setting" on your database model pr. dataelement.



                                                Hope this makes any sense to your question?



                                                A webclient (eg. a browser) does the same thing. The images are "lazy loaded" after the HTML and AJAX is also a "sort of lazy init" if used right.






                                                share|improve this answer












                                                As what I have understood about lazy init so far, is that the program does not load/request all data a once. It waits for the use of it before requesting it from eg. a SQL-server.



                                                If you have a database with a large table joined with a large amount of subtables and you dont require the details joined from the other tabels unless going into "edit" or "view details", then Lazy Init. will help the application to go faster and first "lazy load" the detailsdata upon needed.



                                                In SQL or LINQ you can set this "setting" on your database model pr. dataelement.



                                                Hope this makes any sense to your question?



                                                A webclient (eg. a browser) does the same thing. The images are "lazy loaded" after the HTML and AJAX is also a "sort of lazy init" if used right.







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Jun 11 '09 at 0:29









                                                BerggreenDK

                                                3,39893054




                                                3,39893054






















                                                    up vote
                                                    1
                                                    down vote













                                                    The database examples that have been mentioned so far are good, but it's not restricted to just the data access layer. You could apply the same principles to any situation where performance or memory can be a concern. A good example (although not .NET) is in Cocoa, where you can wait until the user requests a window to actually load it (and its associated objects) from the nib. This can help keep memory usage down and speed up the initial application load, especially when you're talking about things like Preferences windows that won't be needed until some later time, if ever.






                                                    share|improve this answer

























                                                      up vote
                                                      1
                                                      down vote













                                                      The database examples that have been mentioned so far are good, but it's not restricted to just the data access layer. You could apply the same principles to any situation where performance or memory can be a concern. A good example (although not .NET) is in Cocoa, where you can wait until the user requests a window to actually load it (and its associated objects) from the nib. This can help keep memory usage down and speed up the initial application load, especially when you're talking about things like Preferences windows that won't be needed until some later time, if ever.






                                                      share|improve this answer























                                                        up vote
                                                        1
                                                        down vote










                                                        up vote
                                                        1
                                                        down vote









                                                        The database examples that have been mentioned so far are good, but it's not restricted to just the data access layer. You could apply the same principles to any situation where performance or memory can be a concern. A good example (although not .NET) is in Cocoa, where you can wait until the user requests a window to actually load it (and its associated objects) from the nib. This can help keep memory usage down and speed up the initial application load, especially when you're talking about things like Preferences windows that won't be needed until some later time, if ever.






                                                        share|improve this answer












                                                        The database examples that have been mentioned so far are good, but it's not restricted to just the data access layer. You could apply the same principles to any situation where performance or memory can be a concern. A good example (although not .NET) is in Cocoa, where you can wait until the user requests a window to actually load it (and its associated objects) from the nib. This can help keep memory usage down and speed up the initial application load, especially when you're talking about things like Preferences windows that won't be needed until some later time, if ever.







                                                        share|improve this answer












                                                        share|improve this answer



                                                        share|improve this answer










                                                        answered Jun 11 '09 at 0:44









                                                        Marc Charbonneau

                                                        38.6k37081




                                                        38.6k37081






























                                                            draft saved

                                                            draft discarded




















































                                                            Thanks for contributing an answer to Stack Overflow!


                                                            • Please be sure to answer the question. Provide details and share your research!

                                                            But avoid



                                                            • Asking for help, clarification, or responding to other answers.

                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                            To learn more, see our tips on writing great answers.





                                                            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                            Please pay close attention to the following guidance:


                                                            • Please be sure to answer the question. Provide details and share your research!

                                                            But avoid



                                                            • Asking for help, clarification, or responding to other answers.

                                                            • Making statements based on opinion; back them up with references or personal experience.


                                                            To learn more, see our tips on writing great answers.




                                                            draft saved


                                                            draft discarded














                                                            StackExchange.ready(
                                                            function () {
                                                            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f978759%2fwhat-is-lazy-initialization-and-why-is-it-useful%23new-answer', 'question_page');
                                                            }
                                                            );

                                                            Post as a guest















                                                            Required, but never shown





















































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown

































                                                            Required, but never shown














                                                            Required, but never shown












                                                            Required, but never shown







                                                            Required, but never shown







                                                            Popular posts from this blog

                                                            Wiesbaden

                                                            Marschland

                                                            Dieringhausen