【问题标题】:Why is Automapper using so much memory?为什么 Automapper 使用这么多内存?
【发布时间】:2013-06-06 03:12:43
【问题描述】:

我正在使用最新版本的 Automapper (v3.0.0.0-ci1036),当它使用二进制数据转换对象时,它使用了大量的内存。 (10MB 文件为 200MB)。这是一个正在转换的“文件”示例:

class Program
{
    static void Main(string[] args)
    {
        convertObject();
    }

    private static void convertObject()
    {
        var rnd = new Random();
        var fileContents = new Byte[1024 * 1024 * 10];
        rnd.NextBytes(fileContents);

        var attachment = new Attachment { Content = fileContents };

        Mapper.CreateMap<Attachment, AttachmentDTO>();
        Console.WriteLine("Press enter to convert");
        Console.ReadLine();
        var dto = Mapper.Map<Attachment, AttachmentDTO>(attachment);
        Console.WriteLine(dto.Content.Length + " bytes");
        Console.ReadLine();
    }
}

public class Attachment
{
    public byte[] Content { get; set; }
}

public class AttachmentDTO
{
    public byte[] Content { get; set; }
}

我的代码有问题吗,还是我必须停止对包含二进制数据的对象使用自动映射器?

【问题讨论】:

  • 映射后是否会飙升然后恢复正常?
  • 不,它会一直保持这种状态,直到应用程序被杀死
  • 一个原因可能是您使用字节数组:字节数组要求内存中的所有字节都是连续的。

标签: memory-leaks automapper .net-4.5


【解决方案1】:

我不确定,但您的原因可能如下:

您的 C# 应用程序在 .NET 运行时上运行,该运行时可能会使用垃圾收集器清除堆内存。

此技术具有将堆内存碎片化的副作用。因此,例如,您可能分配了 100MB,其中 40% 可用于新变量,这些变量被分割成最大 5MB 的小块。

在这种情况下,当您分配一个 10 MB 的新数组时,.NET 虚拟机没有空间来分配它,即使它有 40 MB 可用空间。

为了解决这个问题,它会将你的可用堆内存提高到 110MB(在最好的情况下)并为你的新字节数组分配新的 10MB。

另见: http://msdn.microsoft.com/en-us/magazine/dd882521.aspx#id0400035

【讨论】:

    猜你喜欢
    • 2012-06-28
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多