Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Stack.TrimExcess() ใน C# : ปรับขนาดความจุให้เท่ากับจำนวนสมาชิกจริง

เมธอด Stack.TrimExcess() ใน C# ใช้สำหรับตั้งค่าความจุ (Capacity) ของ Stack ให้เท่ากับจำนวนสมาชิกจริง (Count) หากจำนวนสมาชิกน้อยกว่าค่าเกณฑ์ (threshold) ที่กำหนดไว้ วิธีนี้ช่วยประหยัดหน่วยความจำเมื่อได้ลบสมาชิกออกไปจำนวนมากแล้ว

รูปแบบไวยากรณ์ (Syntax)

public void TrimExcess();

ตัวอย่างที่ 1: Stack ของจำนวนเต็ม

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Stack stack = new Stack();
        
        // เพิ่มข้อมูล 10 รายการ
        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 have 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 have the element 400? = True
Count of elements in the Stack (updated) = 0

ตัวอย่างที่ 2: Stack ของสตริง

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Stack stack = new Stack();
        
        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

สรุป

  • TrimExcess() ใช้หลังจาก Clear() หรือการลบสมาชิกจำนวนมาก เพื่อปล่อยหน่วยความจำที่ไม่ได้ใช้
  • เมธอดนี้ไม่ทำอะไรหากความจุอยู่ใกล้เคียงกับจำนวนสมาชิกจริง (น้อยกว่า 90% ของความจุ)
  • เหมาะสำหรับกรณีที่ Stack มีขนาดใหญ่ชั่วคราว แล้วลดขนาดลงอย่างมีนัยสำคัญ