The memory allocations (via malloc or new) of C/C + + may take a lot of time.
Worse, as time passes, memory (memory) will be fragmented, so an application will run more slowly. When it runs for a long time and/or performs a lot of memory allocation (release) operations. In particular, you often apply a small chunk of memory, and the heap (heap) becomes fragmented.
Solution: One (possible) solution for your own memory pool is the memory pool (Memory pool).
At boot time, a "Memory pool" (Memory pool) allocates a large chunk of memory, and the block is divided into smaller blocks (smaller chunks). Each time you request a memory space from a memory pool, it is obtained from the previously allocated block (chunks) rather than from the operating system. The biggest advantage is:
1: Very few (few) heap fragments
2: More than the usual memory application/release (e.g. through malloc, new etc) the way quickly in addition, you can get the following benefits: 1: Check whether any one pointer is in the memory Pool 2: Write a "heap dump (heap-dump)" to your hard drive (useful for debugging afterwards)
3: Some kind of "memory leak Detection (Memory-leak detection)": When you do not release all the previously allocated memory, the memory pool (memory pool) throws an assertion (assertion).
SMemoryChunk.h
#ifndef __SMEMORYCHUNK_H__
#define __SMEMORYCHUNK_H__
typedef unsigned char TByte ;
struct SMemoryChunk
{
TByte *Data; //数据
std::size_t DataSize; //该内存块的总大小
std::size_t UsedSize; //实际使用的大小
bool IsAllocationChunk;
SMemoryChunk *Next; //指向链表中下一个块的指针。
};
#endif
IMemoryBlock.h
#ifndef __IMEMORYBLOCK_H__
#define __IMEMORYBLOCK_H__
class IMemoryBlock
{
public :
virtual ~IMemoryBlock() {};
virtual void *GetMemory(const std::size_t &sMemorySize) = 0;
virtual void FreeMemory(void *ptrMemoryBlock, const std::size_t &sMemoryBlockSize) = 0;
};
#endif