Skip to content

PerformanceCounter implementation is taking large memory allocation #1694

Closed

Description

The following code is causing large memory allocation:

return pid == (int)new PerformanceCounter(categoryName, counterName, i, true).RawValue;

Suggested improvement:

        static readonly ConcurrentDictionary<string, Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection>> cache = new ConcurrentDictionary<string, Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection>>();

        private static string FindProcessInstance1(int pid, IEnumerable<string> instances, string categoryName, string counterName)
        {
            Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection> cached;

            DateTime utcNow = DateTime.UtcNow;

            InstanceDataCollectionCollection result = null;

            PerformanceCounterCategory category = null;

            if (cache.TryGetValue(categoryName, out cached))
            {
                category = cached.Item2;

                if (cached.Item1 < utcNow)
                {
                    result = cached.Item3;
                }
            }

            if (result == null)
            {
                if (category == null)
                {
                    category = new PerformanceCounterCategory(categoryName);
                }

                result = category.ReadCategory();

                cache.TryAdd(categoryName, new Tuple<DateTime, PerformanceCounterCategory, InstanceDataCollectionCollection>(utcNow.AddMinutes(1), category, result));
            }

            InstanceDataCollection counters = result[counterName];

            if (counters != null)
            {
                foreach (string i in instances)
                {
                    InstanceData instance = counters[i];

                    if ((instance != null) && (pid == instance.RawValue))
                    {
                        return i;
                    }
                }
            }

            return null;
        }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions