Array.Copy vs Skip and Take in c#

寵の児 提交于 2019-12-23 09:48:00

问题


I was browsing this question and some similar ones:

Getting a sub-array from an existing array

Many places I read answers like this:

Getting a sub-array from an existing array

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

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?


回答1:


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.

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.

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.

(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.)



来源:https://stackoverflow.com/questions/7359496/array-copy-vs-skip-and-take-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!