2

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.

Christian Rau
  • 45,360
  • 10
  • 108
  • 185
jav974
  • 1,022
  • 10
  • 22
  • http://stackoverflow.com/q/8016945/841108 is a very similar question, using Boehm garbage collector (which *will* reuse "unused" memory) – Basile Starynkevitch May 16 '13 at 16:17
  • 13
    The thing you want is called an "object pool". That keyword should help you find enough information to get started. – Dan Hulme May 16 '13 at 16:19
  • For the record, many allocators do this by implementing chunks of memory up front and then handing out pointers from a list. (I think `new` does this, but I don't know much about new/delete) – GRAYgoose124 May 16 '13 at 17:29
  • You may want to look at placement new if you go down the road of rolling your own. – KitsuneYMG May 16 '13 at 18:41

2 Answers2

1

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.

bjskishore123
  • 6,144
  • 9
  • 44
  • 66
0

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.

Mike Dunlavey
  • 40,059
  • 14
  • 91
  • 135