본문 바로가기
프로그래밍/C#

C# 지연 평가(lazy evaluation)에 대해서

by bantomak 2024. 2. 13.

지연 평가란 무엇인가?

컬렉션의 단일 요소가 미리 계산되지 않고 호출되는 시점에서 평가가 이루어지고 실행된다. 즉, 호출시점까지 평가가 지연된다.

 

즉시 평가(eager evaluation)

즉시 평가를 사용하는 경우 모든 값들이 평가되어야지만 수행이 가능하다. 그래서 while(true)로 선언된 경우 끝에 도달하지 못하고 메모리 부족으로 예외가 발생한다.

 

즉시 평가를 사용하는 경우 OutOfMemoryException이 발생한다.

 

지연 평가(lazy evaluation)

지연 평가를 사용하는 경우 while(true)로 선언되어 있다 하더라도 모든 값들을 미리 평가하고 시작하지 않는다. 호출되는 시점에서 필요한 부분까지만 평가하기 때문에 Take(10)에 해당하는 부분까지 지연평가되고 정상적으로 프로그램이 실행된다.

 

 

예제 코드

using System.Collections.Generic;
using System.Linq;
using static System.Console;

// If you replace the lazy call below with the eager one you get an out of memory error
var oneToTen = LazyInfinity().Take(10);

foreach (var n in oneToTen)
{
    WriteLine(n);
}

// "In eager evaluation, the first call to the iterator will result in the entire collection being processed."
// "A temporary copy of the source collection might also be required."
static IEnumerable<int> EagerInfinity()
{
    var i = 0;
    var infinity = new List<int>();

    while (true)
    {
        infinity.Add(++i);
    }

    return infinity;
}

// "In lazy evaluation, a single element of the source collection is processed during each call to the iterator."
static IEnumerable<int> LazyInfinity()
{
    var i = 0;

    while (true)
    {
        yield return ++i;
    }
}

 

참고 사이트

 

Explaining lazy evaluation in C#

Countless were the times I've fired up Visual Studio to write the following example explaining what...

dev.to

댓글