Why is this function faster and why is its multiplicity listed faster than the first?

I needed the TakeLast<T>(int n)-style LINQ function . I encountered this message the StackOverflow: qaru.site/questions/30043 / ... . I liked this answer simply because it was a simple implementation. Then another colleague of mine indicated that it Reverse()should be more expensive than that Skip(length - n). It made me write a test.

Here are the competing features.

public static IEnumerable<T> TakeLast<T>( this IEnumerable<T> c, int n ) {
    return c.Reverse().Take( n ).Reverse();
}


public static IEnumerable<T> TakeLast2<T>( this IEnumerable<T> c, int n ) {
    var count = c.Count();
    return c.Skip( count - n );
}

I have timed the execution of getting the last 10 elements of an enumeration Enumerable.Range( 0, 100000 ). I found that:

  • TakeLast() faster ~ 5x.
  • Enumerations are TakeLast()much faster after the first enumeration.

.NET Sciddle ( , .): http://dotnetfiddle.net/ru7PZE

  • TakeLast() ?
  • TakeLast() , , TakeLast2() ?
+4
1

, . LINQ , , . Count . Count , . , , , . , , , .

, , , , JIT . - , ( ), .

, ( ICollection). , -, , . IList, , - say IQueryable, , , , . , , .

+10

Source: https://habr.com/ru/post/1535382/


All Articles