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

C# Queue.TrimExcess() 메서드 완벽 정리 – 예제 코드와 함께 배우기

C#의 Queue<T>.TrimExcess() 메서드는 큐(Queue)에 저장된 실제 요소 개수가 현재 용량(Capacity)의 90% 미만일 때, 큐의 용량을 실제 요소 개수에 맞게 줄여 메모리를 최적화하는 데 사용됩니다.

큐에서 대량의 요소를 제거한 후에는 내부 배열에 불필요한 여유 공간이 남아 있을 수 있습니다. 이때 TrimExcess()를 호출하면 낭비되는 메모리를 회수할 수 있어 성능과 메모리 효율성 측면에서 유용합니다.

문법(Syntax)

public void TrimExcess();

주요 특징

  • 실제 요소 개수가 현재 용량의 90% 미만인 경우에만 용량이 조정됩니다.
  • 이 임계값(90%)은 잦은 재할당으로 인한 성능 저하를 방지하기 위한 것입니다.
  • 반환값은 없으며(void), 큐 자체의 용량만 변경합니다.

예제 1: 정수형 큐에서 TrimExcess() 사용하기

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      Queue<int> queue = new Queue<int>();
      queue.Enqueue(100);
      queue.Enqueue(200);
      queue.Enqueue(300);
      queue.Enqueue(400);
      queue.Enqueue(500);
      queue.Enqueue(600);
      queue.Enqueue(700);
      queue.Enqueue(800);
      queue.Enqueue(900);
      queue.Enqueue(1000);

      Console.WriteLine("Queue...");
      foreach(int i in queue) {
         Console.WriteLine(i);
      }

      Console.WriteLine("Count of elements in the Queue = " + queue.Count);

      queue.Clear();       // 모든 요소 제거
      queue.TrimExcess();  // 용량을 실제 요소 개수(0)에 맞게 축소

      Console.WriteLine("Count of elements in the Queue [Updated] = " + queue.Count);
   }
}

실행 결과

100
200
300
400
500
600
700
800
900
1000
Count of elements in the Queue = 10
Count of elements in the Queue [Updated] = 0

위 예제에서는 Clear() 메서드로 모든 요소를 제거한 뒤 TrimExcess()를 호출하여, 더 이상 필요하지 않은 내부 버퍼 공간을 해제했습니다.

예제 2: 문자열 큐에서 TrimExcess() 사용하기

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main() {
      Queue<string> queue = new Queue<string>();
      queue.Enqueue("Gary");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");
      queue.Enqueue("Mark");
      queue.Enqueue("Jack");
      queue.Enqueue("Ryan");
      queue.Enqueue("Kevin");

      Console.Write("Count of elements = ");
      Console.WriteLine(queue.Count);

      Console.WriteLine("Does the queue has element Jack? = " + queue.Contains("Jack"));

      queue.TrimExcess();  // 용량 최적화
      queue.Clear();       // 모든 요소 제거

      Console.Write("Count of elements (updated) = ");
      Console.WriteLine(queue.Count);
   }
}

실행 결과

Count of elements = 8
Does the queue has element Jack? = True
Count of elements (updated) = 0

정리

TrimExcess() 메서드는 큐에서 많은 양의 데이터를 삭제한 후 남는 불필요한 메모리 공간을 정리하는 데 효과적인 방법입니다. 다만, 요소 개수가 현재 용량의 90% 이상이라면 아무 작업도 수행하지 않으므로, 호출 시점을 적절히 판단하는 것이 중요합니다. 대용량 컬렉션을 장기간 보관해야 하는 애플리케이션에서 메모리 사용량을 관리할 때 활용해 보시기 바랍니다.