Array.Copy vs Skip and Take in c#

Array.Copy vs Skip and Take in c#(Array.Copy vs Skip and Take in c#)

本文介绍了Array.Copy vs Skip and Take in c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览这个问题和一些类似的问题:

I was browsing this question and some similar ones:

从现有数组中获取子数组

我在很多地方读到这样的答案:

Many places I read answers like this:

获取子数组从现有数组

我想知道为什么 Skip 和 Take 不是数组的恒定时间操作?

What I am wondering is why Skip and Take are not constant time operations for arrays?

反过来,如果它们是恒定时间操作,那么 Skip 和 Take 方法(没有在最后调用 ToArray() )是否具有相同的运行时间而没有执行 Array.Copy 的开销,而且还有更多空间有效率吗?

In turn, if they were constant time operations, won't the Skip and Take method (without calling ToArray() at the end) have the same running time without the overhead of doing an Array.Copy, but also more space efficient?

推荐答案

您必须区分 SkipTake 方法所做的工作,以及使用方法返回的数据.

You have to differentiate between the work that the Skip and Take methods do, and the work of consuming the data that the methods return.

SkipTake 方法本身是 O(1) 操作,因为它们所做的工作不会随着输入大小而缩放.他们只是设置了一个能够从数组中返回项目的枚举器.

The Skip and Take methods themselves are O(1) operations, as the work they do does not scale with the input size. They just set up an enumerator that is capable of returning items from the array.

当您使用枚举器时,工作就完成了.这是一个 O(n) 操作,其中 n 是枚举器产生的项目数.当枚举器从数组中读取时,它们不包含数据的副本,并且只要您使用枚举器,就必须保持数组中的数据完整.

It's when you use the enumerator that the work is done. That is an O(n) operation, where n is the number of items that the enumerator produces. As the enumerators read from the array, they don't contain a copy of the data, and you have to keep the data in the array intact as long as you are using the enumerator.

(如果您在一个无法通过索引(如数组)访问的集合上使用 Skip,则获取第一项是 O(n) 操作,其中 n 是跳过的项目数.)

(If you use Skip on a collection that is not accessible by index like an array, gettting the first item is an O(n) operation, where n is the number of items skipped.)

这篇关于Array.Copy vs Skip and Take in c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Array.Copy vs Skip and Take in c#

基础教程推荐