LINQ to XML 中的延迟执行和迟缓计算 (C#)Deferred Execution and Lazy Evaluation in LINQ to XML (C#)

实现查询和轴操作通常是为了使用延迟执行。Query and axis operations are often implemented to use deferred execution. 本主题解释延迟执行的要求和优点,以及某些实现注意事项。This topic explains the requirements and advantages of deferred execution, and some implementation considerations.

延迟执行Deferred Execution

延迟执行意味着表达式的计算延迟,直到真正需要其实现 值为止。Deferred execution means that the evaluation of an expression is delayed until its realized value is actually required. 当必须操作大型数据集合,特别是在包含一系列链接的查询或操作的程序中操作时,延迟执行可以大大改善性能。Deferred execution can greatly improve performance when you have to manipulate large data collections, especially in programs that contain a series of chained queries or manipulations. 在最佳情况下,延迟执行只允许对源集合的单个循环访问。In the best case, deferred execution enables only a single iteration through the source collection.

LINQ 技术广泛应用了延迟执行,包括在核心 System.Linq 类的成员和不同 LINQ 命名空间中的扩展方法(如 System.Xml.Linq.Extensions)中使用。The LINQ technologies make extensive use of deferred execution in both the members of core System.Linq classes and in the extension methods in the various LINQ namespaces, such as System.Xml.Linq.Extensions.

在迭代器块内使用时,C# 语言可以通过 yield 关键字(以 yield-return 语句形式),直接支持延迟执行。Deferred execution is supported directly in the C# language by the yield keyword (in the form of the yield-return statement) when used within an iterator block. 此类迭代器必须返回类型为 IEnumeratorIEnumerator<T>(或派生类型)的集合。Such an iterator must return a collection of type IEnumerator or IEnumerator<T> (or a derived type).

积极计算与迟缓计算Eager vs. Lazy Evaluation

当您编写实现延迟执行的方法时,还必须确定是使用迟缓计算还是积极计算来实现该方法。When you write a method that implements deferred execution, you also have to decide whether to implement the method using lazy evaluation or eager evaluation.

  • 在迟缓计算 中,每次调用迭代器时都会处理源集合的一个元素。In lazy evaluation, a single element of the source collection is processed during each call to the iterator. 这是实现迭代器的典型方式。This is the typical way in which iterators are implemented.

  • 在积极计算 中,第一次调用迭代器时就会对整个集合进行处理。In eager evaluation, the first call to the iterator will result in the entire collection being processed. 还可能需要源集合的临时副本。A temporary copy of the source collection might also be required. 例如,OrderBy 方法必须在返回第一个元素前对整个集合进行排序。For example, the OrderBy method has to sort the entire collection before it returns the first element.

迟缓计算通常产生更好的性能,因为它将系统开销处理平均分配到整个集合的计算中,并将临时数据的使用降至最低。Lazy evaluation usually yields better performance because it distributes overhead processing evenly throughout the evaluation of the collection and minimizes the use of temporary data. 当然,对于某些操作,除了具体化中间结果之外,再没有其他选择。Of course, for some operations, there is no other option than to materialize intermediate results.

后续步骤Next Steps

本教程的下一个主题将解释延迟执行:The next topic in this tutorial illustrates deferred execution:

请参阅See also