Refresh

List or Hashset


Dùng HashSet<T> khi:
Bạn cần tìm kiếm nhanh, loại bỏ trùng tự động, và không cần thứ tự. 


Dùng List<T> khi:
Bạn cần giữ thứ tự phần tử, cho phép trùng lặp, hoặc truy cập theo vị trí (index).



using System.Diagnostics;

internal class Program
{
    private static void Main()
    {
        int n = 1_000_000;

        // Tạo dữ liệu
        List list = new List();
        HashSet hashSet = new HashSet();

        for (int i = 0; i < n; i++)
        {
            list.Add(i);
            hashSet.Add(i);
        }

        int valueToFind = n - 1; // phần tử cuối

        // Tìm trong List
        Stopwatch sw = Stopwatch.StartNew();
        bool foundInList = list.Contains(valueToFind);
        sw.Stop();
        Console.WriteLine($"List.Contains: {sw.ElapsedTicks} ticks");

        // Tìm trong HashSet
        sw.Restart();
        bool foundInHashSet = hashSet.Contains(valueToFind);
        sw.Stop();
        Console.WriteLine($"HashSet.Contains: {sw.ElapsedTicks} ticks");
    }
}



Đăng nhận xét

Mới hơn Cũ hơn