#StackBounty: #c# #.net #memory Why does a .net program use more VirtualMemorySize64 when the computer has more ram

Bounty: 100

I’ve created a simple test application which allocates 100mb using binary arrays.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace VirtualMemoryUsage
{
class Program
{
    static void Main(string[] args)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine($"IsServerGC = {System.Runtime.GCSettings.IsServerGC.ToString()}");

        const int tenMegabyte = 1024 * 1024 * 10;
        long allocatedMemory = 0;
        List<byte[]> memory = new List<byte[]>();
        for (int i = 0; i < 10; i++)
        {
            //alloc 10 mb memory
            memory.Add(new byte[tenMegabyte]);
            allocatedMemory += tenMegabyte;
        }

        sb.AppendLine($"Allocated memory:    {PrettifyByte(allocatedMemory)}");
        sb.AppendLine($"VirtualMemorySize64: {PrettifyByte(Process.GetCurrentProcess().VirtualMemorySize64)}");
        sb.AppendLine($"PrivateMemorySize64: {PrettifyByte(Process.GetCurrentProcess().PrivateMemorySize64)}");
        sb.AppendLine();
        Console.WriteLine(sb.ToString());
        Console.ReadLine();
    }

    private static object PrettifyByte(long allocatedMemory)
    {
        string[] sizes = { "B", "KB", "MB", "GB", "TB" };
        int order = 0;
        while (allocatedMemory >= 1024 && order < sizes.Length - 1)
        {
            order++;
            allocatedMemory = allocatedMemory / 1024;
        }
        return $"{allocatedMemory:0.##} {sizes[order]}";
    }
 }
}

Note: For this test it is important to set gcserver to true in the app.config

<runtime>
  <gcServer enabled="true"/>  
</runtime>

This then will show the amount of PrivateMemorySize64 and VirtualMemorySize64 allocated by the process.

While PrivateMemorySize64 remains similar on different computers, VirtualMemorySize64 varies quite a bit.
enter image description here

What is the reason for this differences in VirtualMemorySize64 when the same amount of memory is allocated? Is there any documentation about this?


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.