Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7814935
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T05:21:48+00:00 2026-06-02T05:21:48+00:00

I need to implement simple thread-safe memory management preventing fragmentation. I’ve read some articles

  • 0

I need to implement simple thread-safe memory management preventing fragmentation. I’ve read some articles about that like this and this, but I cannot figure out how to start the implementation in C#.

Important points: 95% of requests for memory allocation will be blocks smaller than 1K!

Could somebody please give me some code to start with?

EDITED
I’ve written a Allocator but how I didn’t used pools in Alloc method. How I can change it so it will use pools?

class Allocator
{
       private int _id;

       //TODO: it must be struct!
       class Block
       {
              public int offset;
              public int blockLength;
       }

       private readonly Dictionary<int, Block> idToBlock = new Dictionary<int, Block>();

       private List<byte> rawData;
       private int allocatedBlocksLength;

       // sync
       private readonly object _sync = new object();

       public int Alloc(int count)
       {                  
              rawData.AddRange(new byte[count]);
              idToBlock.Add(_id, new Block { offset = allocatedBlocksLength, blockLength = count });

              var blockId = _id;
              ++_id;
              allocatedBlocksLength += count;

              return blockId;
       }

       public void Free(int id)
       {
              // Search in table
              Block block;
              if (!idToBlock.TryGetValue(id, out block))
                     return;

              // remove object and update all offsets that after our block
              foreach (var kv in idToBlock)
              {
                     if (kv.Key == id)
                           continue;
                     if (kv.Value.offset > block.offset)
                           continue;

                     // changing indexes
                     kv.Value.offset -= block.blockLength;
              }

              // update how much left
              allocatedBlocksLength -= block.blockLength;
       }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T05:21:51+00:00Added an answer on June 2, 2026 at 5:21 am

    If you do need a custom memory manager for your .NET application you should not follow tips (or simply translate code) from the unmanaged world (your second link).

    Memory allocation in .NET environment is quite different, memory gets fragmented much more (because the default allocator privileges the allocation speed) but it can be compacted (so problems of memory fragmentation isn’t really a problem there).

    It’s not your case, but big objects (these days this threshold is set to 85 KB) will be allocated with a different strategy and they won’t be compacted. I think you may need a custom allocator only if you create a lot of short living big objects.

    The first link provide a very naive implementation, did you profile it in a multi-threading environment? Are you sure that it performs better than default allocation, in your case? Even if it performs a little bit better are you sure you need it?

    To make your memory allocator thread-safe you mayuse a different heap for each thread or simply lock your data structures (for example if you keep the list of free memory blocks inside a LinkedList you may lock the structure when you remove a node from the list). It’s not a topic that can be explained in few lines, if you’re really interested to these internals you may read the great “CLR via C#” book.

    When object allocation is really expansive you may use a mechanism of resurrection for your objects but this adds a lot of complexity that must be evaluated, often the price you’ll pay is bigger. You may start with a factory method like:

    MyObject obj = ObjectFactory.Allocate();
    

    Instead of the simple:

    MyObject obj = new MyObject();
    

    In this way you may switch to something else if you really need it but…
    …a small tip: DO NOT PLAY WITH MEMORY ALLOCATION if you’re not really sure of what you’re doing and after you PROFILED your current memory allocation strategy.

    (I’m tempted to use even a bigger font for this message)

    This may be one of the worst thing you can do to your application because you’ll make it slower and your code will be less readable. 99.999% of application won’t need these custom stuff, are you sure your application will need?

    EDIT
    From the example it’s not really clear what you’re doing. Your Alloc method returns an ID but how can you get the allocated data? Anyway…
    If you really need to do something like that…

    • Do not keep a list of bytes, you’ll just waste memory.
    • Do not provide a Free method, you’re in .NET so please rely on GC.
    • Keep a list of available blocks (the Block object). In the Allocate method you’ll search the list of free blocks for a block of the desired size. If you find it you return that block and you remove it from the list. If you do not find the block you have to allocate it and to simply return it to the caller.
    • In the finalizer of the Block object call the GC.ReRegisterForFinalize method and insert the object inside the list of available blocks.

    Very simple implementation, consider as an example not a true program:

    sealed class Block
    {
        internal Block(int size)
        {
            Data = new byte[size];
        }
    
        ~Block()
        {
            BlockFactory.Free(this);
            GC.ReRegisterForFinalize(this);
        }
    
        public byte[] Data
        {
            get;
            private set;
        }
    }
    
    static class BlockFactory
    {
        public static Block Allocate(int size)
        {
            lock (_freeBlocks)
            {
                foreach (Block block in _freeBlocks)
                {
                    if (block.Data.Length == size)
                    {
                        _freeBlocks.Remove(block);
    
                        return block;
                    }
                }
    
                return new Block(size);
            }
        }
    
        internal static void Free(Block block)
        {
            lock (_freeBlocks) _freeBlocks.Add(block);
        }
    
        private static List<Block> _freeBlocks = new List<Block>();
    }
    

    Please note that:

    • This implementation is not efficient at all (in this case a better solution could be a ReadWriterLockSlim instead of lock or another more appropriate data structure instead of List<T>).
    • The search using enumeration is terrible but here it’s just for clarity.
    • To add a finalizer to each object may decrease performances.
    • The example uses Block as container for the data you need (an array of bytes). Is this what you need?

    That said I still think BEFORE you spend any time on this you should check if you need it. Does your application suffers of this issue? Is it the problem? Imagine for example you have a data processing application. Your pipeline is composed of these stages:

    • Acquisition (somehow timed to get data at regular intervals).
    • Processing (various filters).
    • Visualization.

    If you allocate a new buffer for each packet you may create a lot of small objects. I do not really think this may be a problem but you may consider to reuse the same (pre-allocated) buffer in the acquisition stage instead of trying to add complexity to all the application.

    I hope it’s clear what I mean.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I need to implement a simple probe that uses open microsoft rdp protocol. But
I need to implement simple function that is called from multiple threads. The logic
I need to write a simple app that runs two threads: - thread 1:
I'm using CodeIgniter and need an easy to implement captcha. Something simple, nothing too
I need to implement a custom handler for MVC that gives me the first
I need to implement handling of redelivery of JMS messages in the application that
I need to implement a simple spill to disk layer for large volume of
I was hoping to implement a simple XMPP server in Java. What I need
I have simple application when I need to stop a background thread using Stop()
I need to implement a thread pool using pthreads. I could not move forward.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.