Are Linq Skip and Take optimized for arrays? [4.0 release]

This is a common situation for copying a range from an array. C # supports this operation in various ways, for example, using Array.Copy, but also using a combination of Linq Skip and Take.

Starting with .NET 4.0, do the Skip and Run operations carry out significant overhead, or do they recognize (at compile time or at run time) that their target is an array?

To clarify: I mean: a) the time taken to complete the initial bytes and b) the Skip-Take-ToArray combination, which does not suffer from side effects. For example, it new byte[10000].Skip(9999).Take(1).ToArray()can be optimized in this way and will (for large n) be noticeably faster.

+3
source share
3 answers

Skip / continue to work in O (n) because of how LINQ should support knowledge of how elements even in arrays can be changed and how objects should stay up to date with changes. Therefore, although the optimization for O (1) seems trivial, it is not currently implemented.

See: https://edulinq.googlecode.com/hg/posts/40-Optimization.html

John Skeet had a great blog a few years ago that discussed these and other LINQ redefinition issues ( http://codeblog.jonskeet.uk/2011/01/02/reimplementing-linq-to-objects-part-23- take-skip-takewhile-skipwhile / ). This is a wonderful read.

+2

, Skip(k) .MoveNext k, , JITter , , , ' .

:

while (count > 0 && e.MoveNext()) count--;

SkipIterator :

      public bool MoveNext() {
            if (_index < _endIndex) {
                _index++;
                return (_index < _endIndex);
            }
            return false;
        }

SZGenericArrayEnumerator.

( - 4.5.1, 4.0.)

+1

All Articles