c# 集合相关的东西

 

 

c# ArryList 源码分析

c# 实现 单链表(Node)

最近研究集合相关的东西;

1.List 和Dictionry 遍历的比较;

同样是集合,为什么性能会有这样的差距。我们要从存储结构和操作系统的原理谈起。

首先我们清楚List<T>是对数组做了一层包装,我们在数据结构上称之为线性表,而线性表的概念是,在内存中的连续区域,除了首节点和尾节点外,每个节点都有着其唯一的前驱结点和后续节点。我们在这里关注的是连续这个概念。

而HashTable或者Dictionary,他是根据Key而根据Hash算法分析产生的内存地址,因此在宏观上是不连续的,虽然微软对其算法也进行了很大的优化。

由于这样的不连续,在遍历时,Dictionary必然会产生大量的内存换页操作,而List只需要进行最少的内存换页即可,这就是List和Dictionary在遍历时效率差异的根本原因。

2.List和Dictionay 在search的比较:

 由于Dictionay 是基于hash的,所以查找速度是比List快很多的;

 然后我们查看Contains的源码发现:(它实际上是基于For循环的)

 // Contains returns true if the specified element is in the List.
        // It does a linear, O(n) search.  Equality is determined by calling
        // item.Equals().
        //
        public bool Contains(T item) {
            if ((Object) item == null) {
                for(int i=0; i<_size; i++)
                    if ((Object) _items[i] == null)
                        return true;
                return false;
            }
            else {
                EqualityComparer<T> c = EqualityComparer<T>.Default;
                for(int i=0; i<_size; i++) {
                    if (c.Equals(_items[i], item)) return true;
                }
                return false;
            }
        }

发现Dictionay 是基于hash查找的;那什么是hash 查找呢;?=====to do

 public bool ContainsKey(TKey key) {
            return FindEntry(key) >= 0;
        }

 private int FindEntry(TKey key) {
            if( key == null) {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
            }
 
            if (buckets != null) {
                int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
                for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) {
                    if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i;
                }
            }
            return -1;
        }

 3.添加

4.删除

之间的性能比较;

 

posted @ 2017-12-25 14:32  咕-咚  阅读(150)  评论(0编辑  收藏  举报