views:

171

answers:

3

When to go for object pooling using c#? Any good ex...

What are the pro's and con's of maintaining a pool of frequently used objects and grab one from the pool instead of creating a new one?

+4  A: 
  1. When object creation is expensive
  2. When you potentially can experience memory pressure - way too many objects (for instance - flyweight pattern)
Vitaliy Liptchinsky
+3  A: 

I would add memory fragmentation to the list. That can occur when using objects that encapsulate native resources which after they are allocated can not be moved by the Garbage Collector and could potentially fragment the heap.

One real-life example is when you create and destroy lots of sockets. The buffers they use to read/write data have to be pinned in order to be transferred to the native WinSock API which means that when garbage collection occurs, even though some of the memory is reclaimed for the sockets that where destroyed - it could leave the memory in a fragmented state since the GC can't compact the heap after collection. Thus the read/write buffers are prime candidates for pooling. Also, if you're using SocketEventArgs objects, those would also be good candidates.

Here's a good article that talks about the garbage collection process, memory compacting and why object pooling helps.

Miky Dinescu
+4  A: 

There are only two types of resources I can think of that are commonly pooled: Threads and Connections (i.e. to a database).

Both of these have one overarching concern: Scarcity.

  • If you create too many threads, context-switching will waste away all of your CPU time.
  • If you create too many network connections, the overhead of maintaining those connections becomes more work than whatever the connections are supposed to do.
  • Also, for a database, connection count may be limited for licensing reasons.

So the main reason you'd want to create a resource pool is if you can only afford to have a limited number of them at any one time.

Aaronaught