Memory Allocation in JavaScript — Eager vs Lazy Allocation Approach

Memory allocation is the process of reserving complete or partial space (physically or virtual) on the computer to execute an application. The management of memory on a program if not handled in the right way can make the application slow or even stop working, and one of the reasons for that to happen is known in computer science as Memory Leak.

Memory leak occurs when the application allocates spaces in memory and does not releases it after it is used, then the application ends up running out of memory and crashing.

Many programming languages have their approach to prevent memory leaking occuring, inJavaScriptthe lifetime of an object in memory is managed by the garbage collector. The garbage collector is a process that runs periodically and frees up space in memory that is not associated to any reference.

In computing terms the wordslazyandeagerallocationreferto when an application requests memory from the system, and how much it requests up-front.

Eager Allocationis when the application requires the needed space up-front which can cause over-allocation if the system does not exactly know how much memory will be used, but on the other hand the required space is already allocated to be used whenever it is needed.

As opposed to eager allocation,Lazy Allocationrequires space in memory in the run-time (on demand), which costs less to the system as memory is only allocated when needed. But the down side of it is when the application is running with low spare memory and a portion of code needs more memory to continue executing, the application will probably crash.

To illustrate the case let’s suppose we have a program that allocates 100 positions in an array and multiply the first 5 elements by 5.

With aneager allocationapproach the application will allocate the 100 spaces first and then multiply the first 5 elements by 5.

var array = [];var maxElement = 5;

for (i=0; i < 100; i++) array[i] = i;

for (i=0; i < 5; i++) array[i] = i * 5;

//output // => [0, 5, 10, 15, 20, 5, 6, 7, 8, 9, ...]

With alazy allocationapproach the application will allocate and multiply over each iteration through the array.

Conclusion

In conclusion aneagerevaluation will be more efficient when the application uses all the allocated resource for that portion of an expression to run, whereas alazyevaluation will suit better when the application is not aware of the required space of memory to execute.

For more specific information or questions you may have, don't hesitate to contact us at info@qpercom.com