Why is lazy evaluation useful?

后端 未结 22 1633
无人共我
无人共我 2020-11-29 17:04

I have long been wondering why lazy evaluation is useful. I have yet to have anyone explain to me in a way that makes sense; mostly it ends up boiling down to \"trust me\".<

22条回答
  •  鱼传尺愫
    2020-11-29 17:58

    If by "lazy evaluation" you mean like in combound booleans, like in

       if (ConditionA && ConditionB) ... 
    

    then the answer is simply that the fewer CPU cycles the program consumes, the faster it will run... and if a chunk of processing instructions will have no impact on the the outcome of the program then it is unecessary, (and therefore a waste of time) to perform them anyway...

    if otoh, you mean what I have known as "lazy initializers", as in:

    class Employee
    {
        private int supervisorId;
        private Employee supervisor;
    
        public Employee(int employeeId)
        {
            // code to call database and fetch employee record, and 
            //  populate all private data fields, EXCEPT supervisor
        }
        public Employee Supervisor
        { 
           get 
              { 
                  return supervisor?? (supervisor = new Employee(supervisorId)); 
              } 
        }
    }
    

    Well, this technique allows client code using the class to avoid the need to call the database for the Supervisor data record except when the client using the Employee object requires access to the supervisor's data... this makes the process of instantiating an Employee faster, and yet when you need the Supervisor, the first call to the Supervisor property will trigger the Database call and the data will be fetched and available...

提交回复
热议问题