ภาพรวม
Dictionary<TKey, TValue> (generic) เร็วกว่าและปลอดภัยกว่า Hashtable (non-generic) สำหรับ strongly-typed collections
Hashtable
- Non-generic: เก็บ
objectkey และ value - ต้อง boxing/unboxing สำหรับ value types
- ไม่ type-safe - compile time ไม่จับ error ได้
- Thread-safe สำหรับ single writer / multiple readers (ผ่าน
Hashtable.Synchronized)
ตัวอย่าง Hashtable
using System;
using System.Collections;
Hashtable ht = new Hashtable();
ht.Add("E001", "Tom");
ht.Add("E098", "Amit");
ht.Add("E110", "Jack");
foreach (string k in ht.Keys) Console.WriteLine(k + ": " + ht[k]);
Dictionary
- Generic:
Dictionary<TKey, TValue>- type-safe - ไม่ต้อง boxing/unboxing
- ประสิทธิภาพดีกว่า
- Namespace:
System.Collections.Generic - ไม่ thread-safe (ใช้
ConcurrentDictionaryสำหรับ multi-thread)
ตัวอย่าง Dictionary
using System; using System.Collections.Generic; IDictionarydict = new Dictionary (); dict.Add(1, 234); dict.Add(2, 489); dict.Add(3, 599); Console.WriteLine("Dictionary elements: " + dict.Count);
ตารางเปรียบเทียบ
| คุณสมบัติ | Hashtable | Dictionary<TKey,TValue> |
|---|---|---|
| Type Safety | ไม่มี (object) | มี (Generic) |
| Boxing/Unboxing | ต้องใช้ (value types) | ไม่ต้องใช้ |
| Performance | ช้ากว่า | เร็วกว่า |
| Null Key | อนุญาต | ไม่อนุญาต (โยน ArgumentNullException) |
| Key Not Found | คืน null | โยน KeyNotFoundException |
| Thread Safety | มี Synchronized wrapper | ไม่มี (ใช้ ConcurrentDictionary) |
สรุป
ใช้ Dictionary<TKey, TValue> สำหรับโค้ดใหม่ทุกกรณี ยกเว้นต้องรองรับ legacy code หรือ .NET Framework เก่าที่ไม่มี Generics