Previously, we discussed the method of ‘lazy evaluation’ to improve program efficiency, but it is not suitable for all programs. For instance, in cases where a result is guaranteed to be used, employing ‘lazy evaluation’ may actually slow down program efficiency.‘Eager evaluation’ is a method used for such programs, and its basic principle is to perform calculations in advance to enhance program efficiency.1. Real-time Update of Frequently Used ValuesA classic example is obtaining the size in STL. We often use it to get the length of a list or MAP, but recalculating it every time is too time-consuming.Therefore, by using ‘eager evaluation’, we can implement a record of the size value, making it cost-effective for us to retrieve it.2. Record ResultsRetrieving data from files or databases is time-consuming. For example, when we write a student management system, we need to frequently access various student information. Clearly, reading student data from the database every time is inefficient:
void showStuInfo(ID stu_id){ // Retrieve and display student information}
In this case, by using ‘eager evaluation’, we can record the already retrieved student information in a MAP (or other data structures), so that subsequent accesses do not require time-consuming database reads.3. Bulk ExecutionThis is particularly suitable for operations involving IO, networking, and system calls. For instance, when a dynamic array’s length is insufficient, it will expand.
Array<int> a; // Current length is 0
a[10] = 2; // Expand length to 10
a[15] = 3; // Expand length to 15
Each time it expands, the dynamic array must operate new memory, which is costly.Thus, the ‘eager evaluation’ approach is to expand by a larger amount each time. For example, if we need to expand to 10, we expand to 20, so that when the user’s next expansion does not exceed 20, we do not need to operate new memory.Another example is HTTP communication, which is indeed very slow. Therefore, we can return both the required and temporarily unused information in each HTTP communication to avoid frequent HTTP calls.