Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.Copy vs Skip and Take in c#

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?

like image 385
Rob Hinchliff Avatar asked Sep 09 '11 09:09

Rob Hinchliff


1 Answers

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

like image 90
Guffa Avatar answered Oct 27 '22 01:10

Guffa