How to use arraypool and memorypool in C #

Time:2021-7-25

Reusability of resources is a very important means to improve application performance. For example, arraypool and memorypool to be shared in this article effectively reduce memory usage and pressure on GC, so as to improve application performance.

What is arraypool

The system. Buffers namespace provides a high-performance pooling class that can reuse arraysArrayPool, which can be used in scenes where array is often usedArrayPoolTo reduce memory consumption, it is an abstract class, as shown in the following code:

public abstract class ArrayPool
{
}

Imagine that you need to instantiate array multiple times in your business scenario. What are the consequences of doing so? When the GC allocates new array at the same time, it will no longer be used on the heapArrayPoolIt is designed to solve this problem. It dynamically maintains several array objects in the pool when you need tonew arrayYou only need to get it from the pool.

useArrayPool

It can be used in the following three waysArrayPool

  • adoptArrayPool.SharedProperty to getArrayPoolexample.

  • adoptArrayPool.Create()To generateArrayPoolexample.

  • By inheritanceArrayPoolTo generate a self defined subclass.

The following code shows how to get one from arraypoolsize >= 10Array of.

var shared = ArrayPool.Shared;
var rentedArray = shared.Rent(10);

The above code must be noted that although only 10 sizes are rented, the bottom layer will returnMultiple of 2Size = 16 * in Figure 2.

When you don’t need the rentedarray, remember to return it to the arraypool, as shown in the following code.

shared.Return(rentedArray);

The following is the complete code for reference only.

static void Main(string[] args)
        {
            var shared = ArrayPool.Shared;

            var rentedArray = shared.Rent(10);

            for (int i = 0; i < 10; i++)
            {
                rentedArray[i] = i + 1;
            }

            for (int j = 0; j < 10; j++)
            {
                Console.WriteLine(rentedArray[j]);
            }

            shared.Return(rentedArray);

            Console.ReadKey();
        }

Create a custom arraypool

You can also override arraypool to implement custom pooled objects, as shown in the following code:

public class CustomArrayPool : ArrayPool
    {
        public override T[] Rent(int minimumLength)
        {
            throw new NotImplementedException();
        }
        public override void Return(T[] array, bool clearArray = false)
        {
            throw new NotImplementedException();
        }
    }

useMemoryPool

System.MemoryA memory pool object is provided under namespaceMemoryPoolBefore that, you need to create a new memory block every time, which also increases the burden of GCMemoryPoolAfter that, you can take the memory blocks you need directly from the pool.

static void Main(string[] args)
        {

            var  memoryPool = MemoryPool.Shared;

            var rentedArray = memoryPool.Rent(10);

            for (int i = 0; i < 10; i++)
            {
                rentedArray.Memory.Span[i] = i + 1;
            }

            for (int j = 0; j < 10; j++)
            {
                Console.WriteLine(rentedArray.Memory.Span[j]);
            }

            Console.ReadKey();
        }

ArrayPool vs MemoryPool

As can be seen from the above demonstration,ArrayPoolSoarrayRent out in the form of, andMemoryPoolSoMemory blockSo it can be preferred in the scenario of reusing arrayArrayPoolTo improve performance if your code isMemoryThis memory block is preferred if it is used multiple timesMemoryPool

More exciting, welcome to subscribe

Translation link:https://www.infoworld.com/article/3596289/how-to-use-arraypool-and-memorypool-in-c.html

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]