开发者

Linux heap - is doing a ton of new/deletes okay or does the heap become badly fragmented?

开发者 https://www.devze.com 2023-03-31 00:00 出处:网络
I\'m not familiar with how the Linux heap is allocated. I\'m calling malloc()/free() many many times a second, always with the same sizes (there are about 10 structs, each fixed size).Aside from init

I'm not familiar with how the Linux heap is allocated.

I'm calling malloc()/free() many many times a second, always with the same sizes (there are about 10 structs, each fixed size). Aside from init time, none of my memory remains allocated for long periods of time.

Is this considered poor form with the standard heaps? (I'm sure someone will ask 'what heap are you using?' - 'Ugh. The standard static heap' ..meaning I'm unsure.)

Should I instead use a free list or does t开发者_JAVA技巧he heap tolerate lots of the same allocations. I'm trying to balance readability with performance.

Any tools to help me measure?


First of all, unless you have measured a problem with memory usage blowing up, don't even think about using a custom allocator. It's one of the worst forms of premature optimization.

At the same time, even if you do have a problem, a better solution than a custom allocator would be figuring out why you're allocating and freeing objects so much, and fixing the design issue that's causing it.

To address your specific question, glibc's allocator is based on the dlmalloc algorithm, which is near-optimal when it comes to fragmentation. The only way you'll get it to badly fragment memory is the unavoidable way: by allocating objects with radically different lifetimes in alternation, e.g. allocating a large number of objects but only freeing every other one. I think you'll have a hard time working out an allocation pattern that will give worse total memory usage than pools...


Valgrind has a special tool Massif for measuring memory usage. This should help to profile heap allocations.


I think the best performance optimization is to avoid heap allocation wherever it is possible (and reasonable). Whenever an object is stack allocated the compiler will just move the stack pointer up instead of trying to find a free spot or return the allocated memory to some free list.

How is the lifetime of your structures defined? If you can express your object lifetime by scoping then this would indeed increase performance.

0

精彩评论

暂无评论...
验证码 换一张
取 消