Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

A sample of memory pool

1.48/5 (7 votes)
26 Mar 20071 min read 1   972  
Memory Pool

Introduction

Memory allocation in C or C++ language can take lots of time, especially in some efficient software product. If a application always allocate memory, its performance decreases greatly when it is running over a long time. The heap becomes fragments.

the solution to improve the efficiency of memory allocation is using memory pool. It will allocate a big amount of memory on application startup and it will be separate into smaller memory buffer uints. Every time you request memory from the pool, it is taken from previously allocated memory buffer uints, and not from OS. The biggest advantages are

1. Faster than normal memory allocation like malloc/new operator in C,C++ language.

2. very litter heap-fragmention

How does it work?

On application startup, you will allocate a big amount of memory. The big memory block is made up of many buffer units. If the size of buffer that you allocate is smaller than the buffer unit size, the buffer pool will return you the free buffer unit point. One buffer unit is made up of the size of the buffer unit and the buffer memory that you can get.

Using the code

C++
//
// 

<p style="TEXT-ALIGN: left" align="left">    size_t initSize = 1024;

</p>

<p style="TEXT-ALIGN: left" align="left">    //Initialize the memory buffer

</p>

<p style="TEXT-ALIGN: left" align="left">    BufferPool bfA(initSize,20);

</p>

<p style="TEXT-ALIGN: left" align="left">  //allocate memory from the memory pool

</p>

<p style="TEXT-ALIGN: left" align="left">    char *p = bfA.Allocate(100);

</p>

<p style="TEXT-ALIGN: left" align="left">    if(p)

</p>

<p style="TEXT-ALIGN: left" align="left">    {

</p>

<p style="TEXT-ALIGN: left" align="left">  //use the memory buffer

</p>

<p style="TEXT-ALIGN: left" align="left"> 
</p>

<p style="TEXT-ALIGN: left" align="left">  //release memory to the memory pool

</p>

<p style="TEXT-ALIGN: left" align="left">       bfA.Release(p);
    }



</p>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here