简体   繁体   English

验证.NET中的瞬时内存分配差异?

[英]Verifying transient memory allocation differences in .NET?

An app I am working with sees quite large JSON blobs delivered to it on a regular basis so I am attempting to make better use of memory, and if possible, avoid some of the LOH allocations it does for objects above 85Kb when deserializing. 我正在使用的应用程序会定期看到很大的JSON Blob,因此我正在尝试更好地利用内存,并且在可能的情况下,请避免对反序列化时高于85Kb的对象执行某些LOH分配。

I have .NET Memory Profiler and dotMemory but am a little rusty on how they are to be used so I'm looking for some advice. 我有.NET Memory Profiler和dotMemory,但对如何使用它们有些不了解,所以我正在寻找一些建议。

My small console app to profile is simply performing the below scenarios in a tight loop to get a look at the allocations going on. 我要配置的小型控制台应用程序只是在紧密的循环中执行以下方案,以查看正在进行的分配。

byte[] incomingMessage = ....; // LOH
string json = Encoding.UTF8.GetString(incomingMessage); // another LOH
return JsonSerializer.Deserialize(json);

vs

byte[] incomingMessage = ....; // LOH
using (MemoryStream ms = new MemoryStream(incomingMessage))
{
    using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
    {    
        return JsonSerializer.Deserialize(sr);
    }
}

My theory is that I will have less LOH allocs and fragmentation caused by the second code snippet than the first. 我的理论是,与第二个代码段相比,第二个代码段导致的LOH分配和碎片更少。

However, my question is, how do I verify that? 但是,我的问题是,我该如何验证? The aforementioned tools seem to do a great job (particularly .NET Memory Profiler) of comparing snapshots to find leaks etc but it's not obvious what I should be looking for my needs. 前面提到的工具似乎在比较快照以发现泄漏等方面做得很好(尤其是.NET Memory Profiler),但是我应该寻找我的需求并不明显。

Run console application written below under profiler and get snapshot when it will ask for it. 运行下面在profiler下编写的控制台应用程序,并在需要时获取快照。 Then look at all objects from LOH. 然后查看LOH中的所有对象。 Repeat with the second approach. 重复第二种方法。

In case of dotMemory, open "All objects" than " Group by generations ", than objects from LOH. 如果是dotMemory,请打开“所有对象”,然后打开“ LOH”中的对象,然后打开“ 按代分组 ”。

public void Main()
{
  byte[] incomingMessage = ....; // LOH
  string json = Encoding.UTF8.GetString(incomingMessage); // another LOH
  var desj = JsonSerializer.Deserialize(json);
  Console.Writeline("Get snapshot");
  Console.ReadLine();

  // prevent GC to collect them
  GC.KeepAlive(incomingMessage);
  GC.KeepAlive(json);
  GC.KeepAlive(desj);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM