[Posts] C # dictionary set in HashTable, Dictionary, ConcurrentDictionary between the three types

C #, a collection of dictionaries HashTable, Dictionary, ConcurrentDictionary between the three types

C #, HashTable, Dictionary, ConcurrentDictionar all three represent key / value pairs in the collection, but in the end what is the difference, the following details

一, HashTable

HashTable represent key / value pairs. In the .NET Framework, Hashtable System.Collections namespace is a container provided for the processing and performance similar to the key-value key-value pairs, where the key is typically used to search, and is case sensitive key; value for storing data corresponding to the key value. Hashtable in keyvalue key-value pairs are object types, Hashtable can support any type of keyvalue key-value pairs, any non-null object can be used as a key or value.

HashTable is a hash table, he maintained internally a lot of key-value pairs Key-Value, there is a similar index whose value is called the hash value (HashCode), which is based on the Key GetHashCode method through a certain algorithm to obtain get all find operation positioning operation are achieved and find the corresponding Key value value based on the hash value.

Hash function (GetHashCode) so that the address space corresponding to the hash value will not be repeated as much as possible the HashTable.

When a HashTable is occupied more than half the time we get an address by calculating the hash value may be repeated point to the same address, which resulted hash collision.

C # keys right position Position in the HashTable = (HashCode & 0x7FFFFFFF)% HashTable.Length, C # is the solution to hash collisions by detecting method, when the position Postion acquired by the hash value and when occupied, will increase determining a next value of a position displacement x Postion + x is occupied, and if occupied still continues the displacement x is determined position + 2 * x down position is occupied, not occupied if the value is placed therein. When the available space HashTable more and more hours, then get more difficult to get more and more space available, the more time consuming.

Use as follows:

Copy the code
using System;
using System.Collections;

namespace WebApp
{
    class Program
    {
        static void Main(string[] args)
        {   
            Hashtable myHash=new Hashtable();
            
            //插入
            myHash.Add("1","joye.net");
            myHash.Add("2", "joye.net2");
            myHash.Add("3", "joye.net3");

            //key 存在
            try
            {
                myHash.Add("1", "1joye.net");
            }
            catch
            {
                Console.WriteLine("Key = \"1\" already exists.");
            }
            //取值
            Console.WriteLine("key = \"2\", value = {0}.", myHash["2"]);

            //修改
            myHash["2"] = "http://www.cnblogs.com/yinrq/";
            myHash["4"] = "joye.net4";   //修改的key不存在则新增
            Console.WriteLine("key = \"2\", value = {0}.", myHash["2"]);
            Console.WriteLine("key = \"4\", value = {0}.", myHash["4"]);

            //判断key是否存在
            if (!myHash.ContainsKey("5"))
            {
                myHash.Add("5", "joye.net5");
                Console.WriteLine("key = \"5\": {0}", myHash["5"]);
            }
             //移除
            myHash.Remove("1");

            if (!myHash.ContainsKey("1"))
            {
                Console.WriteLine("Key \"1\" is not found.");
            }
            //foreach 取值
            foreach (DictionaryEntry item in myHash)
            {
                Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
            }
            //所有的值
            foreach (var item in myHash.Values)
            {
                Console.WriteLine("Value = {0}",item);
            }

            //所有的key
            foreach (var item in myHash.Keys)
            {
                Console.WriteLine("Key = {0}", item);
            }
            Console.ReadKey();
        }
    }
}
Copy the code

The results are as follows:

More Reference Microsoft official documentation: Hashtable class

二、Dictionary

Dictionary <TKey, TValue> generic class provides a mapping from a set of keys to a set of values. Passing speed to retrieve the values ​​of the key is very fast, close to O (1), because the Dictionary <TKey, TValue> as a class hash table is implemented. Retrieval speed depends on the quality of the hashing algorithm specified for TKey type. TValue may be value types, arrays, or other classes.

Dictionary is a variant of HashTable, which uses a data structure linking the hash table to solve the problem of separation of hash conflict.

Simply use the code:

Copy the code
using System;
using System.Collections;
using System.Collections.Generic;

namespace WebApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<string, string> myDic = new Dictionary<string, string>();
            
            //插入
            myDic.Add("1", "joye.net");
            myDic.Add("2", "joye.net2");
            myDic.Add("3", "joye.net3");

            //key 存在
            try
            {
                myDic.Add("1", "1joye.net");
            }
            catch
            {
                Console.WriteLine("Key = \"1\" already exists.");
            }
            //取值
            Console.WriteLine("key = \"2\", value = {0}.", myDic["2"]);

            //修改
            myDic["2"] = "http://www.cnblogs.com/yinrq/";
            myDic["4"] = "joye.net4";   //修改的key不存在则新增
            Console.WriteLine("key = \"2\", value = {0}.", myDic["2"]);
            Console.WriteLine("key = \"4\", value = {0}.", myDic["4"]);

            //判断key是否存在
            if (!myDic.ContainsKey("5"))
            {
                myDic.Add("5", "joye.net5");
                Console.WriteLine("key = \"5\": {0}", myDic["5"]);
            }
             //移除
            myDic.Remove("1");

            if (!myDic.ContainsKey("1"))
            {
                Console.WriteLine("Key \"1\" is not found.");
            }
            //foreach 取值
            foreach (var item in myDic)
            {
                Console.WriteLine("Key = {0}, Value = {1}", item.Key, item.Value);
            }
            //所有的值
            foreach (var item in myDic.Values)
            {
                Console.WriteLine("Value = {0}",item);
            }

            //所有的key
            foreach (var item in myDic.Keys)
            {
                Console.WriteLine("Key = {0}", item);
            }
            Console.ReadKey();
        }
    }
}
Copy the code

operation result:

More information Reference: the Dictionary class

三、ConcurrentDictionary

Be represented by multiple threads simultaneously access the key / value pairs thread-safe collection.

ConcurrentDictionary < TKey,  TValue>  framework4 arise, simultaneous access by multiple threads, and thread-safe. Dictionary usage with the same lot, but a few more methods. ConcurrentDictionary belong System.Collections.Concurrent namespace according to the MSDN said:

System.Collections.Concurrent namespace provides more thread-safe collection classes. When there are multiple threads concurrently access the collection should be used instead of these classes a corresponding type namespace System.Collections and System.Collections.Generic.

More information: ConcurrentDictionary <TKey, TValue?> Class

 

Fourth, the comparative summary

Data were inserted 5 million, then traverse to see time-consuming.

Copy the code
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;

namespace WebApp
{
    class Program
    {
        static Hashtable _hashtable;
        static Dictionary<string, string> _dictionary;
        static ConcurrentDictionary<string, string> _conDictionary;
        static void Main(string[] args)
        {
            Compare(5000000);
            Console.ReadLine();
            Console.Read();
        }

        public static void Compare(int dataCount)
        {
            _hashtable = new Hashtable();
            _dictionary = new Dictionary<string, string>();
            _conDictionary=new ConcurrentDictionary<string, string>();
            Stopwatch stopWatch = new Stopwatch();

            // Hashtable
            stopWatch.Start();
            for (int i = 0; i < dataCount; i++)
            {
                _hashtable.Add("key" + i.ToString(), "Value" + i.ToString());
            }
            stopWatch.Stop();
            Console.WriteLine("HashTable插" + dataCount + "条耗时(毫秒):" + stopWatch.ElapsedMilliseconds);

            //Dictionary
            stopWatch.Reset();
            stopWatch.Start();
            for (int i = 0; i < dataCount; i++)
            {
                _dictionary.Add("key" + i.ToString(), "Value" +i.ToString());
            }
            stopWatch.Stop();
            Console.WriteLine("Dictionary插" + dataCount + "条耗时(毫秒):" + stopWatch.ElapsedMilliseconds);

            //ConcurrentDictionary
            stopWatch.Reset();
            stopWatch.Start();
            for (int i = 0; i < dataCount; i++)
            {
                _conDictionary.TryAdd("key" + i.ToString(), "Value" + i.ToString());
            }
            stopWatch.Stop();
            Console.WriteLine("ConcurrentDictionary插" + dataCount + "条耗时(毫秒):" + stopWatch.ElapsedMilliseconds);

            // Hashtable
            stopWatch.Reset();
            stopWatch.Start();
            for (int i = 0; i < _hashtable.Count; i++)
            {
                var key = _hashtable[i];
            }
            stopWatch.Stop();
            Console.WriteLine("HashTable遍历时间(毫秒):" + stopWatch.ElapsedMilliseconds);

            //Dictionary
            stopWatch.Reset();
            stopWatch.Start();
            for (int i = 0; i < _hashtable.Count; i++)
            {
                var key = _dictionary["key" + i.ToString()];
            }
            stopWatch.Stop();
            Console.WriteLine("Dictionary遍历时间(毫秒):" + stopWatch.ElapsedMilliseconds);

            //ConcurrentDictionary
            stopWatch.Reset();
            stopWatch.Start();
            for (int i = 0; i < _hashtable.Count; i++)
            {
                var key = _conDictionary["key"+i.ToString()];
            }
            stopWatch.Stop();
            Console.WriteLine("ConcurrentDictionary遍历时间(毫秒):" + stopWatch.ElapsedMilliseconds);
        }
    }
}
Copy the code

运行结果:

可以看出:

大数据插入Dictionary花费时间最少

HashTable is the fastest traversal Dictionary of 1/5, ConcurrentDictionary 1/10

Single-threaded recommended Dictionary, multithreading recommended ConcurrentDictionary or HashTable (Hashtable tab = Hashtable.Synchronized (new Hashtable ()); object gets thread-safe)

Guess you like

Origin www.cnblogs.com/jinanxiaolaohu/p/10936266.html