.NET C#基础教程第22天:ArrayPool

作者:微信公众号:【架构师老卢】
6-10 9:39
186

介绍

由于垃圾回收器的工作量增加,频繁分配和释放较大的缓冲区可能会影响性能。建议我们,一种通过减少垃圾回收周期来回收临时缓冲区和优化性能的机制。ArrayPool<T>

学习目标

  • 了解传统缓冲区分配的问题
  • 使用ArrayPool<T>
  • 使用最佳实践ArrayPool<T>

开发人员的先决条件

  • 基本了解 C# 编程语言。

开始

了解传统缓冲区分配的问题

开发人员使用的一种常见方法是直接分配新的缓冲区

// Allocating a new large buffer
byte[] buffer = new byte[4096];

虽然前面提到的代码片段看起来简洁明了,但它在性能方面存在明显的缺点,尤其是在经常请求大型临时缓冲区的应用程序中。每次分配都会增加堆大小,从而导致更频繁的垃圾回收。

使用ArrayPool<T>

ArrayPool<T>是命名空间的一部分,并提供临时数组,从而减少了对频繁内存分配和 GC 的需求。System.Buffers

// Using ArrayPool<T> to recycle large buffers
var pool = ArrayPool<byte>.Shared;
byte[] buffer = pool.Rent(4096);
try
{
    // Work with the buffer
}
finally
{
    pool.Return(buffer);
}

使用 ArrayPool<T 的最佳实践>

虽然可以显著提高性能,但有一些最佳实践可以确保其有效使用:ArrayPool<T>

  • **正确返回缓冲区:**始终将租用的缓冲区返回到块中的池中,以确保即使发生异常也能返回它们。finally
  • **必要时清除缓冲区:**如果敏感数据存储在缓冲区中,请使用采用布尔参数的方法的重载,该参数指示是否应清除缓冲区。Return
  • **避免长时间保持缓冲:**在最短的时间内租用缓冲区,以保持游泳池的效率并避免耗尽游泳池。

完整代码

创建另一个名为的类,并添加以下代码片段ArrayPoolExample

public static class ArrayPoolExample
{
    public static void BadMethod()
    {
        // Allocating a new large buffer
        byte[] buffer = new byte[4096];
        // Simulate work with the buffer
        FillBuffer(buffer, 0xAA); // Example operation
        Console.WriteLine("Buffer used and will be discarded after method execution.");
    }

    public static void GoodMethod()
    {
        var pool = ArrayPool<byte>.Shared;
        byte[] buffer = pool.Rent(4096);
        try
        {
            // Work with the buffer
            FillBuffer(buffer, 0xBB); // Example operation
            Console.WriteLine("Buffer rented from the pool and returned after use.");
        }
        finally
        {
            pool.Return(buffer);
        }
    }

    public static void FillBuffer(byte[] buffer, byte value)
    {
        for (int i = 0; i < buffer.Length; i++)
        {
            buffer[i] = value;
        }
        // Just an example to simulate buffer usage
        Console.WriteLine($"Buffer filled with value: {value}");
    }
}

从 main 方法执行,如下所示

#region Day 22: Array Pool
static string ExecuteDay22()
{

    Console.WriteLine("Demonstrating BAD Method:");
    ArrayPoolExample.BadMethod();
    Console.WriteLine("\nDemonstrating GOOD Method:");
    ArrayPoolExample.GoodMethod();
    return "Executed Day 22 successfully..!!";
}

#endregion

控制台输出

Demonstrating BAD Method:  
Buffer filled with value: 170  
Buffer used and will be discarded after method execution.  
  
Demonstrating GOOD Method:  
Buffer filled with value: 187  
Buffer rented from the pool and returned after use.

源代码获取:公众号回复消息【code:15974

相关代码下载地址
重要提示!:取消关注公众号后将无法再启用回复功能,不支持解封!
第一步:微信扫码关键公众号“架构师老卢”
第二步:在公众号聊天框发送code:15974,如:code:15974 获取下载地址
第三步:恭喜你,快去下载你想要的资源吧
相关留言评论
昵称:
邮箱:
阅读排行