我想问一个感兴趣的(对我来说)问题。持有一百万件物品的最佳收藏?
如果集合包含很多项目(超过100万),那么什么样的集合是最好的标准性能。
举例来说,我创建了简单的List(10000000)集合并尝试添加大约500000个不同的项目。运行结束后10秒内首先添加30000件物品,但运行后1分钟内收集的物品只有60000件,5分钟后物品150000件。
据我所知,通过添加新项目(因为每个项目都在“类似等于”时间段内创建),内存使用在收集中存在非线性依赖关系。但我可以犯一个错误。
编辑: 你是对的,如果没有样本,它是不够清楚。 我想填充树作为连接列表。 您可以在下面找到示例代码。
public class Matrix
{
public int Id { get; private set; }
public byte[,] Items { get; private set; }
public int ParentId { get; private set; }
public int Lvl { get; private set; }
public int HorizontalCounts
{
get { return 3; }
}
public int VerticalCounts
{
get { return 3; }
}
public Matrix(int id) : this(id, null, 0, 1)
{
}
public Matrix(int id, byte[,] items, int parentId, int lvl)
{
Id = id;
Items = (items ?? (new byte[HorizontalCounts, VerticalCounts]));
ParentId = parentId;
Lvl = lvl;
}
public bool IsEmpty(int hCounter, int vCounter)
{
return (Items[hCounter, vCounter] == 0);
}
public Matrix CreateChild(int id)
{
return (new Matrix(id, (byte[,])Items.Clone(), Id, (Lvl + 1)));
}
}
public class Program
{
public static void Main(string[] args)
{
Matrix node = new Matrix(1);
const int capacity = 10000000;
List<Matrix> tree = new List<Matrix>(capacity) { node };
FillTree(ref tree, ref node);
int l1 = tree.Where(n => (n.Lvl == 1)).Count();
int l2 = tree.Where(n => (n.Lvl == 2)).Count();
int l3 = tree.Where(n => (n.Lvl == 3)).Count();
int l4 = tree.Where(n => (n.Lvl == 4)).Count();
int l5 = tree.Where(n => (n.Lvl == 5)).Count();
}
private static void FillTree(ref List<Matrix> tree, ref Matrix node)
{
for (int hCounter = 0; hCounter < node.HorizontalCounts; hCounter++)
{
for (int vCounter = 0; vCounter < node.VerticalCounts; vCounter++)
{
if (!node.IsEmpty(hCounter, vCounter))
{
continue;
}
int childId = (tree.Select(n => n.Id).Max() + 1);
Matrix childNode = node.CreateChild(childId);
childNode.Items[hCounter, vCounter] = 1;
tree.Add(childNode);
FillTree(ref tree, ref childNode);
}
}
}
}
最新版本:我很抱歉,问题是没有在项目的数量到需要的集合。性能问题在这一行:int childId =(tree.Select(n => n.Id).Max()+ 1);非常感谢您的回答和评论。
您是否有足够的空间容纳百万件物品? – 2010-09-03 12:38:49
这是什么,你试图用这么多项目? – 2010-09-03 12:39:28
我认为这取决于你将要使用的集合。你打算做很多查找还是要迭代集合?也许一个数组会是一个更好的选择? – 2010-09-03 12:40:53