首页 / C# / c# – ToList()的效率[复制]
c# – ToList()的效率[复制]
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – ToList()的效率[复制],小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2290字,纯文字阅读大概需要4分钟。
内容图文
![c# – ToList()的效率[复制]](/upload/InfoBanner/zyjiaocheng/822/a535d2a9f016433396676ad6f3849265.jpg)
参见英文答案 > Is there a performance impact when calling ToList()? 8个
与我合作的很多开发人员使用List而不是IEnumerable(例如)感觉更舒服.我想知道是否对ToList()过度使用有任何性能影响.例如,或者,在订购后将使用ToList()再次获取列表,即
private void ListThinger(List<T> input)
{
input = input.OrderBy(s => s.Thing).ToList();
foreach(var thing in input)
{
// do things
}
}
我的问题是:
> ToList()方法的效率如何?假设内容是POCO,它会创建一个新列表以及需要多少内存吗?如果它是值类型而不是POCO,这会改变吗?
>列表的大小是否会确定效率或列表的大小不确定ToList()的成本?
>如果将一个列表强制转换为IEnumerable,然后在其上调用ToList(),它是否会返回原始对象?
附:我知道单独使用ToList不会破坏任何支持,但是我们正在构建一个高度并发的系统,这个系统目前受CPU约束,所以我正在寻找一些小胜利,当缩放时,它将会带来很大的改进
解决方法:
How efficient is the ToList() method? Will it create a new list and how much memory does that take, assuming the contents are POCOs? Does this change if its a value type rather than a POCO?
ToList()方法通过创建新列表并使用给定集合的项填充它来实现给定集合. Linq.ToList() implementation:
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
return new List<TSource>(source);
}
通过这样做,如果需要,您无法获得被拒绝执行的权力
Will the size of the list determine efficiency or does size of list not determine cost of ToList()?
当它调用Lists复制构造函数并创建一个新列表时,它将对每个项目起作用.因此它将在O(n)中运行 – 意味着列表的大小很重要.有关复制构造函数操作的MSDN文档:
Initializes a new instance of the List class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.
正如@Jason在评论中提到的那样,Copy Constructor很聪明并且很有效但是在不需要的时候这样做仍然是O(n)操作,不必发生
If a list is cast to an IEnumerable and then ToList() is called on it, will it just return the original object?
不会.如上所示,它将创建一个新列表
至于你的示例代码:
input = input.OrderBy(s => s.Thing).ToList();
foreach(var thing in input)
{
// do things
}
当您获得物化列表(而不是可能在执行的执行中执行的IQueriable / IEnumerable)时,在添加后添加ToList不会带来任何好处.
你可以看看这里,也可能会有所帮助:When to use LINQ’s .ToList() or .ToArray()
内容总结
以上是互联网集市为您收集整理的c# – ToList()的效率[复制]全部内容,希望文章能够帮你解决c# – ToList()的效率[复制]所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。