Concise Analysis of memory allocation solutions

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.