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

หาขนาดของ List ใน C#: Count vs Capacity

ภาพรวม

List<T> มีสองคุณสมบัติที่สำคัญ: Count (จำนวนองค์ประกอบจริง) และ Capacity (ขนาดภายในที่จัดสรรไว้) - ต่างกันมาก

โค้ดตัวอย่าง


using System;
using System.Collections.Generic;

public class Demo {
    public static void Main() {
        var list = new List<string>();

        Console.WriteLine($"Initial: Count={list.Count}, Capacity={list.Capacity}");
        // Count=0, Capacity=0

        list.Add("Accessories");
        Console.WriteLine($"After 1 add: Count={list.Count}, Capacity={list.Capacity}");
        // Count=1, Capacity=4 (default growth)

        list.Add("Clothing");
        list.Add("Footwear");
        Console.WriteLine($"After 3 adds: Count={list.Count}, Capacity={list.Capacity}");
        // Count=3, Capacity=4

        list.Add("Bags");
        Console.WriteLine($"After 4 adds: Count={list.Count}, Capacity={list.Capacity}");
        // Count=4, Capacity=4

        list.Add("Watches");
        Console.WriteLine($"After 5 adds: Count={list.Count}, Capacity={list.Capacity}");
        // Count=5, Capacity=8 (doubled)

        // ตั้งค่า Capacity เอง
        list.Capacity = 100;
        Console.WriteLine($"After Capacity=100: Count={list.Count}, Capacity={list.Capacity}");

        // Trim excess
        list.TrimExcess();
        Console.WriteLine($"After TrimExcess: Count={list.Count}, Capacity={list.Capacity}");
    }
}

ผลลัพธ์


Initial: Count=0, Capacity=0
After 1 add: Count=1, Capacity=4
After 3 adds: Count=3, Capacity=4
After 4 adds: Count=4, Capacity=4
After 5 adds: Count=5, Capacity=8
After Capacity=100: Count=5, Capacity=100
After TrimExcess: Count=5, Capacity=5

ความแตกต่างสำคัญ

Propertyความหมายใช้เมื่อไหร่
Countจำนวน element จริงใน Listต้องการรู้ว่ามีข้อมูลกี่ชิ้น (Length)
Capacityขนาด internal array ที่จัดสรรไว้Performance tuning, pre-allocate

แนวทางปฏิบัติ

  • ใช้ Count เพื่อดูจำนวนข้อมูล (เทียบเท่า Length ของ Array)
  • ตั้งค่า Capacity ล่วงหน้าถ้ารู้ประมาณจำนวนข้อมูล (หลีกเลี่ยงการ resize ซ้ำ)
  • TrimExcess() ใช้เมื่อเพิ่มข้อมูลเสร็จแล้ว ต้องการลด memory
  • Capacity` ต้อง `>= Count` เสมอ

ขยายอัตโนมัติ (Growth Strategy)

List ขยาย Capacity โดยประมาณคูณ 2 (doubling) เมื่อเต็ม: 0 → 4 → 8 → 16 → 32 → 64 → 128 ...