Skip to content

HistogramExtensions.GetMaxValue — LINQ over a Hot Path #146

Description

@leecampbell-codeagent

File: HistogramExtensions.cs

public static long GetMaxValue(this HistogramBase histogram)
{
    var max = histogram.RecordedValues().Select(hiv => hiv.ValueIteratedTo).LastOrDefault();
    return histogram.HighestEquivalentValue(max);
}

This iterates the entire histogram via a full RecordedValues() enumeration just to get the last value. The HistogramBase already tracks _maxValue internally; expose it:

public static long GetMaxValue(this HistogramBase histogram)
{
    // Walk backward from CountsArrayLength to find last non-zero index
    for (int i = histogram.CountsArrayLength - 1; i >= 0; i--)
    {
        if (histogram.GetCountAtIndex(i) > 0)
            return histogram.HighestEquivalentValue(histogram.ValueFromIndex(i));
    }
    return 0;
}

Or better: the _maxValue field should be surfaced as a public/internal property (it's already maintained incrementally by UpdatedMaxValue) and returned directly. This turns an O(N) full-scan into O(1).

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions