What is Object Pooling in Csharp ?
Object Pooling is Technique for Efficient Resource Allocation.A Performance Optimization Technique that is based on using Pool of Pre-Allocated Resources Such of Objects For Efficient Resource Allocation . It refers to Reusing of Allocated Memory again and again instead of demanding for more memory as there are chances that more required memory may be not available at runtime (In Running Application)
Why We Need Object Pooling & How It Works?
Have you Heard about Car Pooling ? Let me tell you about that . Car Pooling and Object Pooling is based on Same Concept .
Both are based on Re-using / Proper Utilization of Resource . Instead of Having or using new Resource Each Time We Require .
In Car Pooling We Use Same Resource Car for Multiple Person Instead of Using Car for Each Person . If 4 Person are going to office instead of going from their own car . Car Pooling Tells to Use one car For all 4 People That will save various Natural Resource and money .
Similarly In Object Pooling Memory is assigned to Program Execution and When more objects are required to initialized then instead of demanding and getting more memory resources it waits for previous memory block to get free to be used .
Didn't Got it Don't Worry See Below
Real Time Example of Object Pooling ?
Let’s assume we are running an application which needs allocation of memory for its execution and this application is using Multithreading. This means more than one threads can allocate the same amount of memory simultaneously .
Consider that the application needs 100K memory for its execution and there are 50 threads running simultaneously. All 50 threads will call a method of the application simultaneously.
All the threads will try to allocate 100000 bytes in the heap simultaneously. The OS may not get enough time to swap pages. Thus the application will be under heavy concurrent access, and the application may fail due to misleading memory management!
WE can also create a pool of large Memory Block as much we can according to how much memory we require, at startup. That way, say we create 100 times 100K bytes in memory at startup. If it fails, well enough - we know that right at startup! So there is no surprise at runtime, when the application is live! So we can reduce that number to 75 (from 100) and try again to start our application. Once up and running, we know that there will be barely a need for it to allocate more memory at runtime, as we already have the memory for 75 or 100 arrays allocated. It just uses that as "an object pool", pulls from it, and when done, returns the byte arrays for subsequent use. Chances are that unless truly "concurrent", the already allocated byte arrays will be re-used over and over again, and at runtime, no extra memory will be allocated. If all 75 or 100 arrays are in use, and a 101st request comes in, it will need to allocate an additional memory of only one array - which is easy for the OS to manipulate in RAM.