This question was asked in Thoughtspot MTS-3 interview.
Object pool, also known as resource pool, is a design pattern in which, when an object is requested, it is returned from the pool of available objects; if the object is not available, it will be created.
Objects whose work is done can be released back to the pool so that they can be returned.
Each programming language uses a resource (memory) to function, and every object or variable defined consumes memory, so it is important to manage the memory properly to make the application's performance efficient.
When initializing a class instance is expensive, there is a high rate of class instantiation, and there are few instantiations in use at any given time, object pooling can result in significant performance gains.
The memory is periodically cleaned with the help of garbage collection.
For example,
let arr = new Array(1000).fill(0);
let newArray = arr;
In this, we have created a new array, arr and the variable newArray is pointing to arr, which means newArray is pointing to the memory address of the arr.
In order for garbage collection to collect memory, we will have to set both instances to null.
arr = null;
newArray = null;
Similar to objects, we have to delete them, in order for garbage collection.
const obj = {
name: "learnersbucket"
};
delete obj;
Thus, it is better to maintain a pool of resources and reuse them rather than create a new one and release them when work is done.
Let us try to understand the resource pool with a real world example.
Imagine you are running the resource department in an organization. For a new employee, when they seek items (objects), you first check all the available items in the inventory; if they are available, you provide them to the employee; otherwise, you procure new items in your inventory in case of shortage and then give them to the employees, making an entry into the inventory; similarly, when the employee leaves the organization, they release the items back to the inventory, and the cycle continues.
The same way resource pools also function, follow this flow diagram to get a clear understanding.
