问题描述
现在我有一个算法,动态数组的内存分配:
- 如果数组已满创建两倍大小的新数组,并复制的项目。
- 如果数组是一季度全创建一半大小的新数组,并复制的项目。
这是相当快的算法,动态内存分配,尽管额外的高架复制内容到新分配的数组。
-
更快,
名单,其中是什么; T>
或基于阵列上这样的算法?你会推荐使用? -
确实
名单,其中,T>
使用简单的数组作为内部数据结构
要回答你的问题:
这是事实,C#的名单,其中,T>
实现使用一个内部数组,它是
- 序列化
- 线程安全
- 器具
的IEnumerable< T>
(这意味着它可以LINQ查询,的foreach
ED等)李> - 搜索二进制
等
因此,我想请你用名单,其中,对
,而不是你自己的名单; T&GT。
呵呵,并顺便说一句,如果你想在源$ C $的名单,其中℃; T>
微软,然后在这里它是
List.cs
修改
该人士$ C $ EnsureCapacity
的ç名单,其中,T>
是:
//确保此列表的容量至少是给定的最低
// 值。如果列表的确认当期容量小于min,则
//容量增加到电流容量的两倍或分钟,
//较大者为准。
私人无效EnsureCapacity(INT分钟){
如果(_items.Length<分){
INT newCapacity = _items.Length == 0? _defaultCapacity:_items.Length * 2;
如果(newCapacity<分)newCapacity =分钟;
容量= newCapacity;
}
}
Now I have an algorithm for dynamically allocating memory on an array:
- If array is full I create a new array of twice the size, and copy items.
- If array is one-quarter full I create a new array of half the size, and copy items.
This is fairly fast algorithm for dynamic memory allocation despite the extra over-head of copying the elements to the newly allocated array.
What is the faster,
List<T>
or such an algorithm based on an array? What would you recommend to use?does
List<T>
use simple array as internal data structure?
TO answer your question:
It is true, C#'s List<T>
implementation uses an internal array that is
- Serializable
- Thread-safe
- Implements
IEnumerable<T>
(which means it can be LINQ Queried,foreach
ed etc) - Binary Searched
and so on
Hence, I would ask you to use List<T>
instead of your own List.
Oh and btw, if you want the source code of List<T>
from Microsoft, then here it is
EDIT
The source code of EnsureCapacity
in List<T>
is:
// Ensures that the capacity of this list is at least the given minimum
// value. If the currect capacity of the list is less than min, the
// capacity is increased to twice the current capacity or to min,
// whichever is larger.
private void EnsureCapacity(int min) {
if (_items.Length < min) {
int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2;
if (newCapacity < min) newCapacity = min;
Capacity = newCapacity;
}
}
这篇关于其中算法用于名单,其中,T&GT;动态分配的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!