C#通用列表默认大小或提供一个 [英] C# Generic List with default size or supply one

查看:132
本文介绍了C#通用列表默认大小或提供一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有差异(在性能和内存保存方面)来定义一个默认大小的列表或者指定一个列表。 列表与LT;对象> m_objects = new List< object>(); 



列出< object> m_objects = new List< object>(100);

如果添加更多商品,两者都会增加一倍,对吗?



谢谢,

解决方案

如果您知道您将拥有100多件商品,第二个是更快。



每次它加倍时,它需要复制整个现有数组的内容。对于大型列表,这可能会很慢。

如果指定了容量,则不需要调整大小,直到大于您指定的大小。



如果您从未添加超过100个项目,它只会浪费一点内存(特别是, IntPtr.Size *(容量 - 计数)


I am wondering if there is difference (in the aspect of performance, memory saving) to define a list with a default size or specify one.

List<object> m_objects = new List<object>();

or 

List<object> m_objects = new List<object>(100);

Both will increase the size by doubling up if more items are added, right?

Thanks,

解决方案

If you know that you will have more than 100 items, the second one is faster.

Every time it "doubles up", it needs to copy the contents of the entire existing array. For large lists, this can be slow.
If you specify the capacity, it won't need to resize at all until it gets bigger than what you specified.

If you never add more than 100 items, it justs wastes a bit of memory (specifically, IntPtr.Size * (Capacity - Count))

这篇关于C#通用列表默认大小或提供一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆