C# 스마트 Enum: 최적화

발행: (2026년 1월 2일 오전 11:12 GMT+9)
3 min read
원문: Dev.to

Source: Dev.to

문제: “LINQ 세금”

파트 1에서 매직 넘버를 레코드로 교체했습니다. 특정 상태를 찾기 위해 LINQ를 사용했습니다:

var status = Status.All.SingleOrDefault(x => x.Id == productStatusId);

이 방법은 동작하지만 두 가지 단점이 있습니다:

  • 복잡성 – 상태를 가져올 때마다 LINQ 로직을 반복해야 합니다.
  • 성능 – LINQ는 선형 검색 O(n)을 수행합니다. 상태가 많고 트래픽이 높은 애플리케이션에서는 불필요한 오버헤드가 발생합니다.

이를 최적화하려면 Status 클래스 내부에 private Dictionary를 추가해, 상태 개수와 무관하게 즉시 O(1) 조회가 가능하도록 합니다.

public record StatusValue(int Id, string Description);

public static class Status
{
    public static readonly StatusValue Pending     = new(1, "Pending Approval");
    public static readonly StatusValue Available   = new(2, "Available for Sale");
    public static readonly StatusValue OutOfStock = new(3, "Out of Stock");

    public static readonly StatusValue[] All = { Pending, Available, OutOfStock };

    private static readonly Dictionary _lookup = All.ToDictionary(s => s.Id);

    // O(1) access to the full object
    public static StatusValue? Get(int id) => _lookup.GetValueOrDefault(id);

    // Quick existence check
    public static bool Exists(int id) => _lookup.ContainsKey(id);

    // Accessing properties
    public static string GetDescription(int id) => Get(id)?.Description ?? "Unknown";
}

사용법

LINQ 쿼리를 작성하는 대신, 서비스에서는 이제 다음과 같이 할 수 있습니다:

if (Status.Exists(userInputId))
{
    var label = Status.GetDescription(userInputId);
    Console.WriteLine($"Processing: {label}");
}

추가 자료

  • Live Demo.NET Fiddle에서 직접 시도해 보세요
  • Source CodeGitHub Gist에서 확인하세요
  • Dictionary 클래스 문서 – 공식 .NET docs에서 O(1) 조회 엔진에 대해 자세히 알아보세요.

버전 참고: 이러한 성능 최적화는 .NET 6+ 환경을 대상으로 설계되었습니다.

Back to Blog

관련 글

더 보기 »

C# Smart Enums: 고급

C Smart Enums: advanced의 표지 이미지 https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-upload...

2026년 MiniScript 로드맵

2026 Outlook: 2025가 마무리됨에 따라 2026을 내다볼 시간입니다! MiniScript는 이제 8년이 되었습니다. 많은 프로그래밍 언어는 실제로 …