Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

예제로 배우는 C# Stack.TrimExcess() 메서드 완벽 가이드

C#의 Stack.TrimExcess() 메서드는 스택에 저장된 실제 요소 수가 임계값(threshold) 미만일 경우, 내부 버퍼의 용량(capacity)을 실제 요소 수에 맞게 조정하는 데 사용됩니다. 불필요하게 확보된 여유 메모리를 해제함으로써 메모리 사용 효율을 개선할 수 있습니다.

구문

public void TrimExcess();

이 메서드는 매개변수를 받지 않으며 반환값도 없습니다. 일반적으로 Clear() 메서드로 모든 요소를 제거한 뒤 호출하면, 스택이 점유하고 있던 메모리를 효과적으로 정리할 수 있습니다.

예제 1: int형 스택

using System;
using System.Collections.Generic;
public class Demo {
    public static void Main() {
        Stack<int> stack = new Stack<int>();
        stack.Push(100);
        stack.Push(150);
        stack.Push(175);
        stack.Push(200);
        stack.Push(225);
        stack.Push(250);
        stack.Push(300);
        stack.Push(400);
        stack.Push(450);
        stack.Push(500);
        Console.WriteLine("Elements in the Stack:");
        foreach(var val in stack) {
            Console.WriteLine(val);
        }
        Console.WriteLine("Count of elements in the Stack = "+stack.Count);
        Console.WriteLine("Does Stack has the element 400?= "+stack.Contains(400));
        stack.Clear();
        stack.TrimExcess();
        Console.WriteLine("Count of elements in the Stack (updated) = "+stack.Count);
    }
}

출력 결과

Elements in the Stack:
500
450
400
300
250
225
200
175
150
100
Count of elements in the Stack = 10
Does Stack has the element 400?= True
Count of elements in the Stack (updated) = 0

위 예제에서는 10개의 정수를 스택에 Push한 후, Contains() 메서드로 특정 요소의 존재 여부를 확인했습니다. 이후 Clear()로 모든 요소를 제거하고 TrimExcess()를 호출하면 스택의 요소 수가 0으로 초기화되고, 내부 용량 역시 실제 요소 수에 맞게 축소됩니다.

예제 2: string형 스택

using System;
using System.Collections.Generic;
public class Demo {
    public static void Main() {
        Stack<string> stack = new Stack<string>();
        stack.Push("A");
        stack.Push("B");
        stack.Push("C");
        stack.Push("D");
        stack.Push("E");
        stack.Push("F");
        stack.Push("G");
        stack.Push("H");
        Console.WriteLine("Count of elements = "+stack.Count);
        Console.WriteLine("Elements in Stack...");
        foreach (string res in stack) {
            Console.WriteLine(res);
        }
        Console.Write("Count of elements (updated) = "+stack.Count);
        stack.Clear();
        stack.TrimExcess();
        Console.WriteLine("Count of elements in the Stack (updated) = "+stack.Count);
    }
}

출력 결과

Count of elements = 8
Elements in Stack...
H
G
F
E
D
C
B
A
Count of elements (updated) = 8
Count of elements in the Stack (updated) = 0

스택은 LIFO(Last In, First Out) 구조이기 때문에 마지막에 Push한 "H"부터 순서대로 출력되는 것을 확인할 수 있습니다.

핵심 정리

  • TrimExcess()는 요소 수가 현재 용량의 약 90%(임계값) 미만일 때만 용량을 축소합니다.
  • Clear()로 요소를 모두 제거한 후 호출하면 메모리를 효과적으로 회수할 수 있습니다.
  • 용량이 이미 최적화된 상태라면 이 메서드는 아무 작업도 수행하지 않습니다.