简体   繁体   中英

Hashtable vs Dictionary : Faster?

Probably this question has been answered many times before, in many different ways. I was looking for something more specific, however. Generic Dictionaries, I believe are faster than Hashtables, because they don't need to go through the process of boxing/unboxing.

However, aren't hashtables sorted, which means that searching could be faster? Since the keys are hashed and stored, will there be boxing/unboxing involved whilst searching?

However, isn't hashtable's sorted, which could mean that the search could be faster?

I don't believe that hashtable is sorted.

They share a similar underlying implementation, but Dictionary<TKey, TValue> has been recommended over Hashtable for a long time, which will perform better for value types as it eliminates boxing/unboxing.

See https://referencesource.microsoft.com/#mscorlib/system/collections/hashtable.cs,77

If you really want to know, try benchmarking it. BenchmarkDotNet is a great library for that.

Hashtable is to be considered deprecated with the exception of backcompatibility and a few edge cases such as COM Interop .

Dictionaries also provide type safety and avoid the boxing process (which makes them quicker in general).

However, if you really want to know what performance impact it has, time both types performing an identical operation across two identical datasets using Stopwatch and note the time difference!

The code would look something like:

        Stopwatch clock = new Stopwatch();
        clock.Start();
        foreach (var item in myCol)
        {
            Hashtable ht = new Hashtable();
            //DoSomething()
        }
        clock.Stop();
        var tHash = clock.Elapsed;
        Stopwatch clock = new Stopwatch();
        clock.Start();
        foreach (var item in myCol)
        {
            Dictionary<,> dict = new Dictionary<,>();
            //DoSomething()
        }
        clock.Stop();
        Console.Write($"Delta t = {Math.Abs((tHash - clock.Elapsed).TotalMilliseconds)}"ms);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM