roslyn: Fix CA1827 (DoNotUseCountWhenAnyCanBeUsed) violations in Roslyn.sln
Attempting to migrate Roslyn.sln to latest version (2.9.4) of FxCop analyzer packages leads to a bunch of CA1827 violations where the code is using Count()
Linq invocation when Any()
could be used. This CA rule was added in 2.9.4 analyzer package. A ruleset suppression would be added for this rule and this issue tracks fixing these violations and removing the ruleset entry.
About this issue
- Original URL
- State: open
- Created 5 years ago
- Comments: 17 (11 by maintainers)
We can exclude from this analyzer/fixer the use cases covered by pull/2736 and add replacement of
Any()
alongside withCount()
to pull/2736.Performance wise, it should be the best compromise.
As for users, it might be a bit more confusing, but they might learn from it.
When the framework changes, we’ll change the analyzers/fixers accordingly.
The analyzer attempts to avoid an O(n) amount of work during the switch from Count() to Any(). This is a more acute problem for general-purpose code than avoiding an O(1) allocation on a fast path. I would further argue that code sensitive enough to performance where the special-case behavior matters would be using more concrete types than
IEnumerable<T>
. I do not see any issues with the rule as-presented which would alter or special-case its behavior.Just the ones that don’t take a predicate.
As I noted, that might be something to do for .NET Core. It will not be changed in .NET Framework. So the rule is problematic on .NET Framework at the very least.
There are also downsides to changing it, which is why it hasn’t been done thus far, e.g. the extra interface checks add overhead, which is less impactful when the alternative is a potentially long iteration through every element, and more impactful when at most one element will be considered.