Skip to content

Question/Suggestion is GcStats forcing a GC.Collect when it doesn't need to #811

@Lexcess

Description

@Lexcess

In the method GetAllocatedBytes in GcStats this code line 128
There is the following code.

        private static long GetAllocatedBytes()
        {
            { mono section omitted }

            // "This instance Int64 property returns the number of bytes that have been allocated by a specific 
            // AppDomain. The number is accurate as of the last garbage collection." - CLR via C#
            // so we enforce GC.Collect here just to make sure we get accurate results
            GC.Collect();

#if CLASSIC
            return AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize;
#elif NETSTANDARD2_0
            if (RuntimeInformation.IsFullFramework) // it can be a .NET app consuming our .NET Standard package
                return AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize;
    {Rest of method omitted}

The code and the comments imply that the GC.Collect is only there to make the call to MonitoringTotalAllocatedMemorySize as accurate as possible. Given that only some runtimes use that method my question is shouldn't the above section instead read like:

        private static long GetAllocatedBytes()
        {
            { mono section omitted }

#if CLASSIC
            // "This instance Int64 property returns the number of bytes that have been allocated by a specific 
            // AppDomain. The number is accurate as of the last garbage collection." - CLR via C#
            // so we enforce GC.Collect here just to make sure we get accurate results
            GC.Collect();
            return AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize;
#elif NETSTANDARD2_0
            if (RuntimeInformation.IsFullFramework)
            {
                // it can be a .NET app consuming our .NET Standard package
                GC.Collect();
                return AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize;
            }
  {Rest of method omitted}

This would remove the unnecessary GC.Collect() calls when not running on FX. While the collects are happening outside of the measurement it seems superfluous and also potentially impacts other measurements you might want to make (if for example you wanted to see if performance degrades due to GC over lots of runs).

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions