Skip to content

Gendarme.Rules.Performance.ReviewLinqMethodRule(git)

Sebastien Pouliot edited this page Mar 2, 2011 · 1 revision

ReviewLinqMethodRule

Assembly: Gendarme.Rules.Performance
Version: git

Description

Linq extension methods operate on sequences of values so they generally have linear time complexity. However you may be able to achieve better than linear time performance if you use a less general method or take advantage of a method provided by an Sytem.Collections.Generic.IEnumerable subclass.

Examples

Bad example:

public string FirstOrMissing (IEnumerable<string> sequence, string missing)
{
    // Count () is O(n)
    if (sequence.Count () > 0) {
        return sequence.First ();
    }
    return missing;
}
public void Append (List<string> lines, string line)
{
    // Last () is O(n)
    if (lines.Count == 0 || lines.Last () != line) {
        lines.Add (line);
    }
}

Good example:

public string FirstOrMissing (IEnumerable<string> sequence, string missing)
{
    // We don't need an exact count so we can use the O(1) Any () method.
    if (sequence.Any ()) {
        return sequence.First ();
    }
    return missing;
}
public void Append (List<string> lines, string line)
{
    // Lines is a List so we can use the O(1) subscript operator instead of
    // the Last () method.
    if (lines.Count == 0 || lines [lines.Count - 1] != line) {
        lines.Add (line);
    }
}

Notes

  • This rule is available since Gendarme 2.6

Source code

You can browse the latest source code of this rule on github.com

Clone this wiki locally