.NET에서 유형이 가비지 수집되지 않는다는 것이 잘 알려져 있습니다. 즉, 유형을 가비지 수집하지 않아도됩니다. 즉, f.ex로 재생하는 경우입니다. Reflection.Emit, AppDomains 등을 언로드 할 때 조심해야한다. 적어도 물건이 어떻게 작동 하는지를 이해하는 방법이다.MakeGenericType/제네릭 형식이 가비지 수집됩니까?
일반 유형 이 가비지 수집 된 것인지 궁금합니다. 정확히 말하면 MakeGenericType
으로 생성 된 제네릭입니다. 예를 들어 사용자 입력을 기반으로합니다.
public interface IRecursiveClass
{
int Calculate();
}
public class RecursiveClass1<T> : IRecursiveClass
where T : IRecursiveClass,new()
{
public int Calculate()
{
return new T().Calculate() + 1;
}
}
public class RecursiveClass2<T> : IRecursiveClass
where T : IRecursiveClass,new()
{
public int Calculate()
{
return new T().Calculate() + 2;
}
}
public class TailClass : IRecursiveClass
{
public int Calculate()
{
return 0;
}
}
class RecursiveGenericsTest
{
public static int CalculateFromUserInput(string str)
{
Type tail = typeof(TailClass);
foreach (char c in str)
{
if (c == 0)
{
tail = typeof(RecursiveClass1<>).MakeGenericType(tail);
}
else
{
tail = typeof(RecursiveClass2<>).MakeGenericType(tail);
}
}
IRecursiveClass cl = (IRecursiveClass)Activator.CreateInstance(tail);
return cl.Calculate();
}
static long MemoryUsage
{
get
{
GC.Collect(GC.MaxGeneration);
GC.WaitForFullGCComplete();
return GC.GetTotalMemory(true);
}
}
static void Main(string[] args)
{
long start = MemoryUsage;
int total = 0;
for (int i = 0; i < 1000000; ++i)
{
StringBuilder sb = new StringBuilder();
int j = i;
for (int k = 0; k < 20; ++k) // fix the recursion depth
{
if ((j & 1) == 1)
{
sb.Append('1');
}
else
{
sb.Append('0');
}
j >>= 1;
}
total += CalculateFromUserInput(sb.ToString());
if ((i % 10000) == 0)
{
Console.WriteLine("Current memory usage @ {0}: {1}",
i, MemoryUsage - start);
}
}
Console.WriteLine("Done and the total is {0}", total);
Console.WriteLine("Current memory usage: {0}", MemoryUsage - start);
Console.ReadLine();
}
}
당신이 재귀의 끝을 표시하는 '꼬리'클래스, 일반 유형이 정의 '가능성 재귀'되어 볼 수 있듯이 : :-)
그래서 나는 다음 테스트 케이스를 구축 .GC.TotalMemoryUsage
이 속임수가되지 않도록 작업 관리자를 열었습니다.
지금까지 그렇게 좋았습니다. 내가 한 다음 일은이 짐승을 태우고 '추억'을 기다리는 동안 ... 나는 내 기대와 달리 - 아니요, 시간이 지남에 따라 더 많은 메모리를 소비하는 것으로 나타났습니다. 사실, 시간이 지남에 따라 메모리 소비가 약간 감소합니다.
누군가 설명해 주시겠습니까? 일반 유형은 실제로 GC에서 수집합니까? 그리고 만약에 그렇다면 ... 반사도 있습니다. 쓰레기 수거 사례가 있습니까?
는 다음 확인. –
아마도 이것이 [JIT 컴파일러로 제네릭을 컴파일하는 방법은 무엇입니까?] (http://stackoverflow.com/questions/5342345/how-do-generics-get-compiled-by-the-jit-compiler) –