728x90
예외 코드
class SimpleSum
{
public Func<int> GetSum;
public SimpleSum(int max)
{
int[] array = Enumerable.Range(0, max).ToArray();
GetSum = () =>
{
return array.Sum();
};
}
}
class Program
{
static void Main(string[] args)
{
var list = new List<SimpleSum>();
for (int i = 0; i < 100000; i++)
{
list.Add(new SimpleSum(100000));
}
}
}
수정코드
class SimpleSum
{
public Func<int> GetSum;
public SimpleSum(int max)
{
//int[] array = Enumerable.Range(0, max).ToArray();
IEnumerable<int> enumAll = Enumerable.Range(0, max);
GetSum = () =>
{
return enumAll.Sum();
};
}
}
int[]를 IEnumerable<int>로 바꾸어 배열을 열거 객체로 바꾼다
큰 배열은 메모리를 엄청나게 잡아 먹지만 열거 객체는 데이터 자체를 저장하는 게 아니라 필요한 데이터를 반복해서 가져온다.
즉 메모리를 압박하지 않게된다. 열거할 때 계산이 이루어지기 때문에 데이터가 바뀌어도 변경된 합계를 구할 수 있다.
728x90
'c#' 카테고리의 다른 글
[C#] 파일 확실하게 닫기 (0) | 2023.01.26 |
---|---|
[C#] 의미없는 구조체 (0) | 2023.01.26 |
[C#] 무명 메서드2 가이드와 장점 (0) | 2023.01.25 |
[C#] 무명 메서드 (0) | 2023.01.25 |
LiveCharts 코드 비하인드 (0) | 2023.01.19 |