দ্রুত তুলনা
| বিষয় | SortedList<TKey, TValue> | SortedDictionary<TKey, TValue> |
|---|---|---|
| অন্ডারলাইং স্ট্রাকচার | দুটি প্যারালেল অ্যারে (Key[] + Value[]) | রেড-ব্ল্যাক ট্রি (Self-balancing BST) |
| মেমরি | কম (কনটিগুয়াস অ্যারে) | বেশি (নোড অবজেক্ট, পয়েন্টার) |
| ইনসারশন/ডিলিশন | O(n) — শিফটিং দরকার | O(log n) — ট্রি রিব্যালেন্স |
| লুকআপ (Key) | O(log n) — বাইনারি সার্চ | O(log n) — ট্রি ট্রাভার্সাল |
| ইন্ডেক্সによる অ্যাক্সেস | হ্যাঁ (list[index], GetKey(index)) | না (শুধু Key দিয়ে) |
| মেমরি ফ্র্যাগমেন্টেশন | কম | বেশি (হিপে ছড়িয়ে থাকা নোড) |
| সর্টেড অর্ডার | হ্যাঁ (কী অনুযায়ী সর্টেড) | হ্যাঁ (কী অনুযায়ী সর্টেড) |
কোনটি কখন ব্যবহার করবেন?
✅ SortedList ব্যবহার করুন যখন:
- ডেটা প্রায়_static_ (কম ইনসারশন/ডিলিশন)
- ইন্ডেক্স দ্বারা অ্যাক্সেস দরকার (
list[5], পেইজিনেশন) - মেমরি সংবেদনশীল অ্যাপ্লিকেশন
- ছোট থেকে মাঝারি আকারের ডেটাসেট (< 1000-5000 এলিমেন্ট)
✅ SortedDictionary ব্যবহার করুন যখন:
- ফ্রিকোয়েন্ট ইনসারশন/ডিলিশন/আপডেট
- বড় ডেটাসেট (হাজার হাজার এলিমেন্ট)
- শুধু কী-ভিত্তিক লুকআপ দরকার
- থ্রেড-সেফ অপারেশন দরকার (ConcurrentSortedDictionary নেই, লক দরকার)
উদাহরণ: SortedList
using System;
using System.Collections.Generic;
var sortedList = new SortedList<int, string> {
{ 3, "Three" },
{ 1, "One" },
{ 2, "Two" }
};
// ইনডেক্স দিয়ে অ্যাক্সেস
Console.WriteLine(sortedList.Keys[0]); // 1
Console.WriteLine(sortedList.Values[0]); // One
Console.WriteLine(sortedList[1]); // One (Key=1)
// কী দিয়ে অ্যাক্সেস
Console.WriteLine(sortedList[2]); // Two
উদাহরণ: SortedDictionary
using System;
using System.Collections.Generic;
var sortedDict = new SortedDictionary<int, string> {
{ 3, "Three" },
{ 1, "One" },
{ 2, "Two" }
};
// শুধু কী দিয়ে অ্যাক্সেস
Console.WriteLine(sortedDict[1]); // One
// sortedDict.Keys[0] // ❌ Compile error - Keys হলো IEnumerable, ইন্ডেক্সার নেই
// কিন্তু Keys কলেকশন থেকে লুপ করা যায়
foreach (var key in sortedDict.Keys) {
Console.WriteLine($"{key}: {sortedDict[key]}");
}
পারফরম্যান্স বেঞ্চমার্ক (রেফারেন্স)
Operation | SortedList (1000 items) | SortedDictionary (1000 items) -------------------|-------------------------|------------------------------ Insert (sequential)| ~0.5 ms | ~1.2 ms Insert (random) | ~5 ms | ~1.5 ms Lookup | ~0.01 ms | ~0.02 ms Memory | ~40 KB | ~80 KB Index Access | ✅ O(1) | ❌ Not supported
নোট: প্রকৃত সংখ্যা মেশিন, .NET ভার্সন, ডেটা টাইপের ওপর নির্ভর করবে।
উভয়ের কমন ইন্টারফেস: IDictionary<TKey, TValue>
// পলিমরফিকভাবে ব্যবহার
IDictionary<int, string> dict = new SortedDictionary<int, string>();
// বা
IDictionary<int, string> dict = new SortedList<int, string>();