简体   繁体   中英

Handle memory, garbage collector like

I have a piece of code that does a lot of memory allocation.

I would like to know if there were a pattern that I can implement to reuse previously deleted memory (because I build a lot of temporary objects that allocate memory like int* , char* , etc.. but it can be very huge).

My purpose is optimization, so I'd like to reuse the memory and not "delete" it even when using temporary object.

It may not be clear enough, let me know so that I can post some code to show you the problem.

Delegate the creation of your temporary objects to a class.

As pointed by Dan, you need to implement a memory manager Or Pool by overloading new and delete operators in that class.

Allocate big chunk of memory when first time new is called and divide that into fixed size blocks. Keep using these blocks for temporary objects. When delete is called, just update the allocation status of that block.

Delete the big chunk once you are done with using temporary objects.

All I do is make sure the object has a spare pointer in it. Then instead of "delete" I just keep a linked list of previously used objects, and push it on the front of the list. Instead of "new" I pop one off. If the list is empty, that's when I make a truly new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM