欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

解析从源码分析常见的基于Array的数据结构动态扩容机制的详解

程序员文章站 2023-12-19 16:01:34
本文的写作冲动来源于今晚看到的老赵的一则微博“大家知道system.collections.generic.list是一种什么样的数据结构?内部的元素是怎...

本文的写作冲动来源于今晚看到的老赵的一则微博“大家知道system.collections.generic.list<t>是一种什么样的数据结构?内部的元素是怎么存放的?还有dictionary<tkey,tvalue>呢?…”。

查了一下书,如果参考数据结构和算法里介绍的线性表合哈希表的特点,非常官方的答案就类似:list<t>是一种线性的内存连续分配的存储结构,元素是顺序存放的;它的优点是内存连续分配,相对节省空间,在设定长度范围内增加元素开销很小;缺点是查找复杂度为o(n),不如哈希结构o(1)复杂度来的快,如插入节点超过指定长度需要重新开辟内存,开销很大云云。而dictionary<tkey,tvalue>则是哈希结构,优点blahblahblah缺点blahblahblah。回答结束。

然后再看老赵微博下面的回答,似乎很不统一,多数认为是基于数组实现的,但是…擦,看一圈都没有老赵满意的答案。以前看过文章听说过stringbuilder和hashtable内部是怎么实现的,以及一个笼统的列表内存扩容两倍说,但是一直不知道具体细节也不太肯定,所以我也很想知道答案。老赵说稍微有点儿好奇心的程序员都应该会去看看两个实现的源代码。世上无难事只怕有心人,要是真的有心人顺便还应该不论对错记录一下自己的学习心得,哈哈。

注:如果你是新手,建议直接到此为止,不要再往下看了。实在好奇想知道答案,最简单正确也是我的偶像老赵所推荐的做法当然是自己查msdn和framework源码。为了不误导人,本文再加上一个标签:无责任乱写。

一、stringbuilder

stringbuilder有6种构造函数,直接通过无参构造函数创建对象比较常见。msdn(中文)里说“此实现的默认容量是 16,默认的最大容量是 int32.maxvalue”。默认容量是16,16什么呢,这话怎么说得这么模糊呢?反汇编跟一下源码,看到它的构造函数最终要调用一个方法:

复制代码 代码如下:

public unsafe stringbuilder(string value, int startindex, int length, int capacity)
        {
            if (capacity < 0)
            {
                throw new argumentoutofrangeexception("capacity", environment.getresourcestring("argumentoutofrange_mustbepositive", new object[]
    {
     "capacity"
    }));
            }
            if (length < 0)
            {
                throw new argumentoutofrangeexception("length", environment.getresourcestring("argumentoutofrange_mustbenonnegnum", new object[]
    {
     "length"
    }));
            }
            if (startindex < 0)
            {
                throw new argumentoutofrangeexception("startindex", environment.getresourcestring("argumentoutofrange_startindex"));
            }
            if (value == null)
            {
                value = string.empty;
            }
            if (startindex > value.length - length)
            {
                throw new argumentoutofrangeexception("length", environment.getresourcestring("argumentoutofrange_indexlength"));
            }
            this.m_maxcapacity = 2147483647;
            if (capacity == 0)
            {
                capacity = 16; //默认值
            }
            if (capacity < length)
            {
                capacity = length;
            }
            this.m_chunkchars = new char[capacity]; //字符数组容量初始化
            this.m_chunklength = length;
            fixed (char* ptr = value)
            {
                stringbuilder.threadsafecopy(ptr + (intptr)startindex, this.m_chunkchars, 0, length);
            }
        }

默认容量16,其实估计是指默认预分配的字符串容量为16个字符。

再分析其中带两个参数的:public stringbuilder(int capacity, int maxcapacity),它的主要实现如下:

复制代码 代码如下:

       public stringbuilder(int capacity, int maxcapacity)
        {
            if (capacity > maxcapacity)
            {
                throw new argumentoutofrangeexception("capacity", environment.getresourcestring("argumentoutofrange_capacity"));
            }
            if (maxcapacity < 1)
            {
                throw new argumentoutofrangeexception("maxcapacity", environment.getresourcestring("argumentoutofrange_smallmaxcapacity"));
            }
            if (capacity < 0)
            {
                throw new argumentoutofrangeexception("capacity", environment.getresourcestring("argumentoutofrange_mustbepositive", new object[]
    {
     "capacity"
    }));
            }
            if (capacity == 0)
            {
                capacity = math.min(16, maxcapacity); //将最大容量和默认容量16进行比较,取较小的
            }
            this.m_maxcapacity = maxcapacity;
            this.m_chunkchars = new char[capacity];
        }

这里就有一个疑问:通常我们实现字符串拼接的时候,肯定不能保证字符串的容量不大于默认容量16,如果大于16,stringbuilder是如何实现这种动态扩容效果的呢,总不能一下子就留足内存吧?我们看一下常见的append(string value)方法是如何实现的:
复制代码 代码如下:

        public unsafe stringbuilder append(string value)
        {
            if (value != null)
            {
                char[] chunkchars = this.m_chunkchars;
                int chunklength = this.m_chunklength;
                int length = value.length;
                int num = chunklength + length;
                if (num < chunkchars.length) //没有超过最大容量
                {
                    if (length <= 2) //2个及2个以下字符拼接
                    {
                        if (length > 0)
                        {
                            chunkchars[chunklength] = value[0];
                        }
                        if (length > 1)
                        {
                            chunkchars[chunklength + 1] = value[1];
                        }
                    }
                    else
                    {
                        fixed (char* smem = value)
                        {
                            fixed (char* ptr = &chunkchars[chunklength])
                            {
                                string.wstrcpy(ptr, smem, length); //好像c函数 看不到内部实现
                            }
                        }
                    }
                    this.m_chunklength = num;
                }
                else
                {
                    this.appendhelper(value);
                }
            }
            return this;
        }

上面的代码中,对于超过拼接后默认最大容量的字符串的逻辑在appendhelper中,appendhelper最终是通过下面的方法实现的:
复制代码 代码如下:

      internal unsafe stringbuilder append(char* value, int valuecount)
        {
            int num = valuecount + this.m_chunklength;
            if (num <= this.m_chunkchars.length)
            {
                stringbuilder.threadsafecopy(value, this.m_chunkchars, this.m_chunklength, valuecount);
                this.m_chunklength = num;
            }
            else
            {
                int num2 = this.m_chunkchars.length - this.m_chunklength;
                if (num2 > 0)
                {
                    stringbuilder.threadsafecopy(value, this.m_chunkchars, this.m_chunklength, num2);
                    this.m_chunklength = this.m_chunkchars.length;
                }
                int num3 = valuecount - num2;
                this.expandbyablock(num3); //终于看到扩容函数了
                stringbuilder.threadsafecopy(value + (intptr)num2, this.m_chunkchars, 0, num3);
                this.m_chunklength = num3;
            }
            return this;
        }

接着来分析扩容函数expandbyablock:
复制代码 代码如下:

     private void expandbyablock(int minblockcharcount)
        {
            if (minblockcharcount + this.length > this.m_maxcapacity)
            {
                throw new argumentoutofrangeexception("requiredlength", environment.getresourcestring("argumentoutofrange_smallcapacity"));
            }
            int num = math.max(minblockcharcount, math.min(this.length, 8000)); //重新分配数组的空间计算
            this.m_chunkprevious = new stringbuilder(this);
            this.m_chunkoffset += this.m_chunklength;
            this.m_chunklength = 0;
            if (this.m_chunkoffset + num < num)
            {
                this.m_chunkchars = null;
                throw new outofmemoryexception();
            }
            this.m_chunkchars = new char[num]; //数组重新分配空间
        }

从上面的直白分析我们可明显看出,实例化一个stringbuilder必然要初始化并维护一个内部数组char[] m_chunkchars。而学过c语言和数据结构的应该都知道,数组对于它的创建需要预先给出一定的连续分配的内存空间,它并不支持在原有的内存空间的基础上去扩展,所以数组对于动态内存分配是极为不利的,但是基本的数据结构如字符串和线性表就是基于数组实现的。

接着简单看了一下其他几个常用拼接方法和索引器,内部实现大致一样,几乎都是对字符数组的操作逻辑。有兴趣大家不妨也看看源码。

分析到这里,我们可以大胆假设:stringbuilder内部实现的字符串操作最终是通过字符数组char[] m_chunkchars进行处理的。想一想也对啊,如果stringbuildr的实现是通过string加等于减等于地拼过来接过去那就逊掉了。

不能忽视的是它的扩展容量的算法,最关键的就是下面这行代码:

int num = math.max(minblockcharcount, math.min(this.length, 8000));其实是非常简单的数学方法,stringbuilder内部的maxchunksize默认为8000,大家可以评估一下,如果进行多次拼接,字符串长度随机一点,内存分配情况会怎么样,8000这个数字有没有道理。据传说和gc内部算法一样,framework一些常用类的内部实现也遵循着平衡的设计,不知真假。

二、基于array的可动态扩容的线性结构

大家应该都非常熟悉,就像stringbuilder一样,framework中很多集合都有动态扩容效果。比如我们熟悉的线性集合arraylist,泛型list,queue,stack等等,这些都是直接基于array而实现的。

那么基于array的集合它们内部是如何实现动态扩容的,扩容的量是怎么控制的?也许我们早有耳闻,就是动态扩展的容量是上一次已有容量的两倍,到底是不是这样的呢?带着疑问我们挑一个最常见的集合泛型list<t>分析一下。

和stringbuilder分析法类似,我们也从构造函数和add方法着手分析。

无参构造函数如下:

复制代码 代码如下:

     public list()
        {
            this._items = list<t>._emptyarray;
        }


_items是个泛型数组(private t[] _items;泛型数组好像不能这么说?),通过构造函数它肯定有默认初始容量了,_emptyarray肯定初始化分配了一定空间,猜对了吗?_emptyarray定义如下:

  private static readonly t[] _emptyarray = new t[0];
看看有一个参数的:

复制代码 代码如下:

        public list(int capacity)
        {
            if (capacity < 0)
            {
                throwhelper.throwargumentoutofrangeexception(exceptionargument.capacity, exceptionresource.argumentoutofrange_neednonnegnum);
            }
            this._items = new t[capacity];
        }

这回直接给_items new了一个数组对象。

好,再来一个传入初始集合的:

复制代码 代码如下:

public list(ienumerable<t> collection)
        {
            if (collection == null)
            {
                throwhelper.throwargumentnullexception(exceptionargument.collection);
            }
            icollection<t> collection2 = collection as icollection<t>;
            if (collection2 != null)
            {
                int count = collection2.count;
                this._items = new t[count];
                collection2.copyto(this._items, 0);
                this._size = count;
                return;
            }
            this._size = 0;
            this._items = new t[4];
            using (ienumerator<t> enumerator = collection.getenumerator())
            {
                while (enumerator.movenext())
                {
                    this.add(enumerator.current);
                }
            }
        }

到这里估计大家都看到关键的地方了:每个构造函数都要对_items 变量进行初始化,而这个_items 正是一个数组(如我们所知,泛型list确实是基于数组实现的)。

再来分析下增删改查中的增加也就是add方法:

复制代码 代码如下:

       public void add(t item)
        {
            if (this._size == this._items.length)
            {
                this.ensurecapacity(this._size + 1); //扩容函数
            }
            this._items[this._size++] = item; //通过索引器赋值,添加元素
            this._version++;
        }

我们目标明确,终于找到了扩容函数ensurecapacity:
复制代码 代码如下:

        private void ensurecapacity(int min)
        {
            if (this._items.length < min)
            {
                int num = (this._items.length == 0) ? 4 : (this._items.length * 2); //容量=当前的长度的两倍
                if (num < min)
                {
                    num = min;
                }
                this.capacity = num; //当前数组容量赋值
            }
        }

到这里,我们看到,添加一个元素的时候,如果容量没超过预分配的数组空间大小,直接通过下面的索引器赋值:
复制代码 代码如下:

      public t this[int index]
        {
            [targetedpatchingoptout("performance critical to inline across ngen image boundaries")]
            get
            {
                if (index >= this._size)
                {
                    throwhelper.throwargumentoutofrangeexception();
                }
                return this._items[index];
            }
            [targetedpatchingoptout("performance critical to inline across ngen image boundaries")]
            set
            {
                if (index >= this._size)
                {
                    throwhelper.throwargumentoutofrangeexception();
                }
                this._items[index] = value;
                this._version++;
            }
        }

如果新增的项超过了现有数组的最大容量,通过扩容函数进行容量再分配(再new一个数组对象),在函数ensurecapacity中,我们看到:

int num = (this._items.length == 0) ? 4 : (this._items.length * 2); //容量=当前的长度的两倍这里进行了数组容量的重新计算,方法很简单。最重要的是给属性capacity赋值:

this.capacity = num; //当前数组容量赋值这个属性的set里面包含了数组new的操作:

复制代码 代码如下:

    public int capacity
        {
            [targetedpatchingoptout("performance critical to inline across ngen image boundaries")]
            get
            {
                return this._items.length;
            }
            set
            {
                if (value < this._size)
                {
                    throwhelper.throwargumentoutofrangeexception(exceptionargument.value, exceptionresource.argumentoutofrange_smallcapacity);
                }
                if (value != this._items.length)
                {
                    if (value > 0)
                    {
                        t[] array = new t[value]; //重新初始化一个数组
                        if (this._size > 0)
                        {
                            array.copy(this._items, 0, array, 0, this._size);
                        }
                        this._items = array; //新数组指向原数组,原数组丢弃
                        return;
                    }
                    this._items = list<t>._emptyarray;
                }
            }
        }

分析到这里我们完全可以通过伪代码总结出集合的扩容算法:
复制代码 代码如下:

public void add(t item)
{
   判断当前元素个数是否等于它预设定的容量

   if(等于)
   {
       重新分配内存空间(前一次的空间乘以二)
       利用array.copy方法把元素复制到新分配的空间
   }

   设置元素的当前位置
   currentindex++;
   this[currentindex] = item;
}


也许有人会问,重新分配内存空间时直接简单的乘以2会不会太草率了,这样不是容易造成内存空间的浪费吗?ms的实现也不都是非常严谨的嘛?

确实,缓冲区扩容的时候,如数据量较大,很明显会造成内存浪费,泛型list提供了一个方法叫trimexcess用来解决内存浪费的问题:

复制代码 代码如下:

       public void trimexcess()
        {
            int num = (int)((double)this._items.length * 0.9); //当前数组空间容量乘以0.9
            if (this._size < num)
            {
                this.capacity = this._size; //重新设置数组空间
            }
        }

原理也就是一个简单的数学方法,你在外部调用一次或多次,它就会自动帮你平衡空间节省内存了。

有一个非常常用的功能就是判断元素是否在列表里,方法名就是熟悉的contains,看代码果然是o(n)复杂度:

复制代码 代码如下:

    public bool contains(t item)
        {
            if (item == null)
            {
                for (int i = 0; i < this._size; i++)
                {
                    if (this._items[i] == null)
                    {
                        return true;
                    }
                }
                return false;
            }
            equalitycomparer<t> @default = equalitycomparer<t>.default;
            for (int j = 0; j < this._size; j++)
            {
                if (@default.equals(this._items[j], item))
                {
                    return true;
                }
            }
            return false;
        }

大功告成,哈哈,我惊诧极了目瞪口呆,泛型list果然也是基于数组的,而且我们现在可以理直气壮地说我很清楚它的内部扩容实现算法。此时我真想拍着肩膀对自己说,哥们你辛苦了,太有成就感了,抓紧时间多想想你喜欢的姑娘吧……我果然又红光满面了。

然后,再查看源码,发现很多核心方法的实现都直接对_items数组进行操作,并多次调用了array的静态方法,所以我们一定不可小视数据结构数组(array)。

反汇编查看array的源码,发现增删改查方法相当之丰富,哪位有心人可以挖掘挖掘里面使用了多少种经典算法(比如binarysearch听说用了二分查找),反正感觉它是被我大大低估了。至少现在我们知道,经常使用的常用数据结构如stringbuilder、arraylist,泛型list,queue,stack等等都是基于array实现的。不要小看了它,随着framework的发展,也许未来还会不断出现基于array的新的数据结构的出现。

三、基于array的可动态扩容的哈希结构

平时开发中经常使用的其他的一些数据结构如hashtable,泛型dictionary,hashset以及线程安全容器concurrentdictionary等等也可以动态扩容。下面从hashtable源码入手简单分析下。

先从无参构造函数开始:

复制代码 代码如下:

      public hashtable()
            : this(0, 1f)
        {
        }

无参构造函数最终需要调用的构造方法如下:
复制代码 代码如下:

      public hashtable(int capacity, float loadfactor)
        {
            if (capacity < 0)
            {
                throw new argumentoutofrangeexception("capacity", environment.getresourcestring("argumentoutofrange_neednonnegnum"));
            }
            if (loadfactor < 0.1f || loadfactor > 1f)
            {
                throw new argumentoutofrangeexception("loadfactor", environment.getresourcestring("argumentoutofrange_hashtableloadfactor", new object[]
    {
     0.1,
     1.0
    }));
            }
            this.loadfactor = 0.72f * loadfactor; //负载因子 熟悉又陌生的0.72
            double num = (double)((float)capacity / this.loadfactor);
            if (num > 2147483647.0)
            {
                throw new argumentexception(environment.getresourcestring("arg_htcapacityoverflow"));
            }
            int num2 = (num > 3.0) ? hashhelpers.getprime((int)num) : 3; //初始化数组空间
            this.buckets = new hashtable.bucket[num2]; //原来是bucket结构构造的数组
            this.loadsize = (int)(this.loadfactor * (float)num2);
            this.iswriterinprogress = false;
        }

正如我们所知,哈希函数的计算结果是一个存储单位地址,每个存储单位称为桶,而buckets不正是我们要找的存储散列函数计算结果的哈希桶吗?原来它也是个数组。这里大家看到了吗?this.buckets原来就是一个struct结构数组,心里好像一下子就有底了。

好,接着找动态扩容函数,从add方法入手吧:

      public virtual void add(object key, object value)
        {
            this.insert(key, value, true);
        }
跟踪到insert方法,代码一下子变得内容丰富,但是我们直接看到了一个判断语句:

          if (this.count >= this.loadsize)
            {
                this.expand();
            }
上面这个if判断一目了然,expand不就是扩展的意思吗?跟进去:

      private void expand()
        {
            int prime = hashhelpers.getprime(this.buckets.length * 2); //直接乘以2 好像还有个辅助调用获取素数 hashhelpers.getprime
            this.rehash(prime); //重新hash
        }
有个rehash函数,再跟进去:

复制代码 代码如下:

        private void rehash(int newsize)
        {
            this.occupancy = 0;
            hashtable.bucket[] newbuckets = new hashtable.bucket[newsize]; //重新定义哈希buckets
            for (int i = 0; i < this.buckets.length; i++) //竟然是遍历旧buckets,然后填充新buckets
            {
                hashtable.bucket bucket = this.buckets[i];
                if (bucket.key != null && bucket.key != this.buckets)
                {
                    this.putentry(newbuckets, bucket.key, bucket.val, bucket.hash_coll & 2147483647);
                }
            }
            thread.begincriticalregion();
            this.iswriterinprogress = true;
            this.buckets = newbuckets; //旧buckets的引用改变为新填充的newbuckets
            this.loadsize = (int)(this.loadfactor * (float)newsize);
            this.updateversion();
            this.iswriterinprogress = false;
            thread.endcriticalregion();
        }

果然又看到了数组的重新定义和再赋值:this.buckets = newbuckets;

这不就又回到老路上来了吗?再查查array出现的频率,哈希表很多方法的实现也还是数组操作来操作去的。到这里,忍不住想起周星驰电影里的话:打完收功。

但是还没完,有一个动态扩容容量的计算问题,是和泛型列表一样的直接乘以2吗?在expand函数里我们看到了下面这一行:

int prime = hashhelpers.getprime(this.buckets.length * 2);
很显然,乘以2以后还需要一个辅助函数hashhelpers.getprime(看命名就知道是获取素数)的运算,hashhelpers.getprime代码如下:

复制代码 代码如下:

 internal static int getprime(int min)
  {
   if (min < 0)
   {
    throw new argumentexception(environment.getresourcestring("arg_htcapacityoverflow"));
   }
   for (int i = 0; i < hashhelpers.primes.length; i++)
   {
    int num = hashhelpers.primes[i];
    if (num >= min)
    {
     return num;
    }
   }
   for (int j = min | 1; j < 2147483647; j += 2)
   {
    if (hashhelpers.isprime(j))
    {
     return j;
    }
   }
   return min;
  }
 }

获取素数的实现好像还蛮熟悉的。继续跟踪hashhelpers,发现它的primes数组列举了最小为3,最大为7199369的素数。如果你的哈希表容量不是特别大,3到7199369的素数足够使用了(符合二八原则),否则哈希表扩容的时候需要在2147483647这个数字范围内通过hashhelpers.isprime来判断并动态生成素数。所以简单地说哈希表扩容后的容量是原来的两倍并不准确,这个就和哈希算法对素数的要求有直接关系,在不太精确的情况下我们可以认为约等于两倍。

出于好奇顺便查看了一下泛型字典的源码,它的内部实现包含了buckets和entries两个结构数组,还发现哈希结构的容器通常内部算法果然都比较绕。我猜它们的实现也不同程度地利用了数组的特点,说到底应该也是基于array实现的吧(看到没,不知道就算无责任乱写)?其他的几种常见哈希结构的容器还没有认真看,有兴趣大家可以直接查看源码详细分析一下,挑典型的一两个对比着看应该非常有效果。

欢迎大家畅所欲言说说你所知道的基于array的其他数据结构,这里我就不再班门弄斧贻笑大方了。


思考:抛一个弱弱的疑问向大家求证:实现容器的动态特性是不是必须要基于数组呢,基于数组的实现是唯一的方式吗?

上一篇:

下一篇: