开发者

.net Fast Memory Allocation

In my application there are some cases that relatively small objects, (max 50 bytes) e.g. message classes for logging purposes, must be created and freed (by GC) frequently during the execution of the program. So I am worried about the overhead of dynamic allocation of these objects. As stated in this question there are some usable fast memory allocators for native code.

Is there a concept of fast memory allocation in .Net or is fast memory allocation needed in .Net? If not what can be used to speed up that kind of implementation? (Maybe some kind of a preallocated object pool.) Should I worry about the 开发者_Python百科overhead?


You should not worry about the overhead unless and until your profiler gives you hard data to support the worrying.

I suppose that you might be able to implement an allocator using unsafe code, but would the hair-pulling and the effort be worth it? You have to profile to know.


As it behooves a well designed memory allocator, there is only one way to allocate garbage collected memory. It is very fast, allocating merely requires adjusting a pointer. Much faster than the allocator that native code has to use. Which has a much more difficult job to do, once native memory is allocated it cannot be moved anymore. Which makes it hard to write an allocator that doesn't suffer from fragmentation. The counter-measures add overhead. Not an issue in a GC heap, it can compact.

You cannot improve on the speed of the GC allocator.


If the objects are small and short lived I wouldn't worry too much. They most likely get collected with the Gen0 GC, which is usually relatively cheap.

You can implement a pool, but in my experience this is only necessary if you allocate large objects(If I recall correctly objects are placed on the large object heap if they're bigger than about 80kB) or very many(many millions per second) objects.

So first implement it normally. And only if you see that your program spends a lot of time in the GC you should worry about your allocations. Most likely you're thinking about a premature optimization.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜