다음을 통해 공유


중간 구체화(C#)

주의하지 않으면 경우에 따라 쿼리에서 컬렉션의 조기 구체화를 발생시켜 애플리케이션의 메모리 및 성능 프로필을 크게 변경할 수 있습니다. 일부 표준 쿼리 연산자는 단일 요소를 생성하기 전에 원본 컬렉션을 구체화합니다. 예를 들어 Enumerable.OrderBy 먼저 전체 소스 컬렉션을 반복한 다음 모든 항목을 정렬한 다음, 마지막으로 첫 번째 항목을 생성합니다. 즉, 정렬된 컬렉션의 첫 번째 항목을 가져오는 데 비용이 많이 듭니다. 이후 각 항목은 비용이 들지 않습니다. 이것은 의미가 있습니다. 그렇지 않으면 해당 쿼리 연산자가 수행할 수 없습니다.

예: ToList를 호출하여 구체화하는 메서드를 추가합니다.

다음은 체인 쿼리 예제(C#)를 변경하는 예제입니다. 메서드가 원본을 반복하기 전에 AppendString를 호출하도록 변경되어, 이로 인해 구체화가 발생합니다.

public static class LocalExtensions
{
    public static IEnumerable<string>
      ConvertCollectionToUpperCase(this IEnumerable<string> source)
    {
        foreach (string str in source)
        {
            Console.WriteLine("ToUpper: source >{0}<", str);
            yield return str.ToUpper();
        }
    }

    public static IEnumerable<string>
      AppendString(this IEnumerable<string> source, string stringToAppend)
    {
        // the following statement materializes the source collection in a List<T>
        // before iterating through it
        foreach (string str in source.ToList())
        {
            Console.WriteLine("AppendString: source >{0}<", str);
            yield return str + stringToAppend;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        string[] stringArray = { "abc", "def", "ghi" };

        IEnumerable<string> q1 =
            from s in stringArray.ConvertCollectionToUpperCase()
            select s;

        IEnumerable<string> q2 =
            from s in q1.AppendString("!!!")
            select s;

        foreach (string str in q2)
        {
            Console.WriteLine("Main: str >{0}<", str);
            Console.WriteLine();
        }
    }
}

이 예제는 다음과 같은 출력을 생성합니다.

ToUpper: source >abc<
ToUpper: source >def<
ToUpper: source >ghi<
AppendString: source >ABC<
Main: str >ABC!!!<

AppendString: source >DEF<
Main: str >DEF!!!<

AppendString: source >GHI<
Main: str >GHI!!!<

이 예제에서는 ToList 호출이 AppendString가 첫 번째 항목을 생성하기 전에 전체 원본을 열거하도록 하는 것을 확인할 수 있습니다. 원본이 큰 배열인 경우 애플리케이션의 메모리 프로필이 크게 변경됩니다.

이 자습서의 마지막 문서에 표시된 대로 표준 쿼리 연산자를 함께 연결할 수도 있습니다.

참고하십시오