简体   繁体   中英

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.

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.

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.

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.

Run console application written below under profiler and get snapshot when it will ask for it. Then look at all objects from LOH. Repeat with the second approach.

In case of dotMemory, open "All objects" than " Group by generations ", than objects from 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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