C# LINQ 优化
优化以下类型的语句的正确方法是什么:
IEnumerable<T> sequence = BuildSequence();
// 'BuildSequence' makes some tough actions and uses 'yield return'
// to form the resulting sequence.
现在,如果我愿意只采用一些第一个元素,我可以使用类似的东西:
sequence.Take(5);
所以,如果我的序列来自 BuildSequence
实际上包含数千个元素,我显然不希望构建所有元素,因为我只需要其中 5 个。
LINQ
是否可以优化此类操作,还是我必须自己发明一些东西?
What would be the proper way of optimizing the following kind of statements:
IEnumerable<T> sequence = BuildSequence();
// 'BuildSequence' makes some tough actions and uses 'yield return'
// to form the resulting sequence.
Now, if I'm willing to take only some of the first elements, I could use something like:
sequence.Take(5);
And so, if my sequence from BuildSequence
actually contains several thousands of elements, I obviously don't want all of them to be constructed, because I would only need 5 of them.
Does LINQ
optimize this kind of operations or I would have to invent something myself?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
迭代器块(
yield return
)为您处理这个问题;迭代器块是一个流 API;工作仅在迭代器(或Dispose()
)上的每次MoveNext()
调用期间发生。由于Take()
also 不会读取整个流,因此保留了此行为。但请注意,某些操作需要在本地缓冲数据 - 尤其是
GroupBy
和OrderBy
;但只要您使用非缓冲操作,就可以了。例如:
The iterator block (
yield return
) handles this for you; an iterator block is a streaming API; work only happens during eachMoveNext()
call on the iterator (or onDispose()
). BecauseTake()
also doesn't read the entire stream, this behaviour is preserved.Note, however, that some operations need to buffer the data locally -
GroupBy
andOrderBy
most notably; but as long as you use non-buffering operations, you are fine.For example:
您应该看一下:
LINQ 和 Deferred执行
You should take a look on this:
LINQ and Deferred Execution