| 속성 | 값 |
|---|---|
| 규칙 ID | CA1841 |
| 제목 | Prefer Dictionary Contains 메서드 |
| 범주 | 성능 |
| 수정 사항이 주요 변경인지 여부 | 주요 변경 아님 |
| .NET 10에서 기본적으로 사용하도록 설정 | 제안 사항 |
원인
이 규칙은 사전 자체에서의 Contains 또는 Keys 메서드 호출로 바꿀 수 있는 Values의 IDictionary<TKey,TValue> 또는 ContainsKey 컬렉션에서의 ContainsValue 메서드 호출을 찾습니다.
규칙 설명
Contains 또는 Keys 컬렉션에서 Values를 호출하면 사전 자체에서 ContainsKey 또는 ContainsValue를 호출하는 것보다 비용이 더 많이 들 수 있습니다.
- 대부분의 사전 구현에서 키 및 값 컬렉션을 지연 인스턴스화하므로
Keys또는Values컬렉션에 액세스하면 추가 할당이 발생할 수 있습니다. - 키 또는 값 컬렉션에서 명시적 인터페이스 구현을 사용하여 IEnumerable<T>의 메서드를 숨기는 경우 ICollection<T>의 확장 메서드를 호출하게 될 수 있습니다. 이로 인해 성능이 저하될 수 있으며, 키 컬렉션에 액세스할 때는 특히 그렇습니다. 대부분의 사전 구현에서는 키에 대한 빠른 O(1) 포함 검사를 제공할 수 있지만,
Contains의 IEnumerable<T> 확장 메서드는 일반적으로 느린 O(n) 포함 검사를 수행합니다.
위반 문제를 해결하는 방법
위반 문제를 해결하려면 dictionary.Keys.Contains 또는 dictionary.Values.Contains 호출을 각각 dictionary.ContainsKey 또는 dictionary.ContainsValue 호출로 바꿉니다.
다음 코드 조각에서는 위반 문제의 예제와 해결 방법을 보여 줍니다.
using System.Collections.Generic;
// Importing this namespace brings extension methods for IEnumerable<T> into scope.
using System.Linq;
class Example
{
void Method()
{
var dictionary = new Dictionary<string, int>();
// Violation
dictionary.Keys.Contains("hello world");
// Fixed
dictionary.ContainsKey("hello world");
// Violation
dictionary.Values.Contains(17);
// Fixed
dictionary.ContainsValue(17);
}
}
Imports System.Collection.Generic
' Importing this namespace brings extension methods for IEnumerable(Of T) into scope.
' Note that in Visual Basic, this namespace is often imported automatically throughout the project.
Imports System.Linq
Class Example
Private Sub Method()
Dim dictionary = New Dictionary(Of String, Of Integer)
' Violation
dictionary.Keys.Contains("hello world")
' Fixed
dictionary.ContainsKey("hello world")
' Violation
dictionary.Values.Contains(17)
' Fixed
dictionary.ContainsValue(17)
End Sub
End Class
경고를 표시하지 않는 경우
문제의 코드가 성능에 중요하지 않은 경우 이 규칙에서 경고를 표시하지 않도록 해도 안전합니다.
경고 표시 안 함
단일 위반만 표시하지 않으려면 원본 파일에 전처리기 지시문을 추가하여 규칙을 사용하지 않도록 설정한 후 다시 사용하도록 설정합니다.
#pragma warning disable CA1841
// The code that's violating the rule is on this line.
#pragma warning restore CA1841
파일, 폴더 또는 프로젝트에 대한 규칙을 사용하지 않도록 설정하려면 none에서 심각도를 으로 설정합니다.
[*.{cs,vb}]
dotnet_diagnostic.CA1841.severity = none
자세한 내용은 방법: 코드 분석 경고 표시 안 함을 참조하세요.
참고 항목
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET