简体   繁体   English

处理内存,垃圾收集器之类的

[英]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). 我想知道是否可以实现一种模式来重用以前删除的内存(因为我建立了许多临时对象来分配内存,例如int*char*等,但是它可能非常大)。

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. 正如Dan所指出的,您需要通过重载该类中的new和delete运算符来实现内存管理器或Pool。

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时,只需更新该块的分配状态即可。

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. 如果列表为空,那是我创建一个真正的新列表的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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