2013-08-13 7 views
6

Ho un List<T>, chiamato L, contenente N elementi.IEnumerable <T> .Last() ottimizzato per l'elenco <T>?

È L.Last(), il metodo di estensione IEnumerable<T>, che consente di scorrere tutti gli elementi N in tempo lineare?

O è ottimizzato internamente per avere la costanza di rendimento in tempo L[L.Count - 1]?

+2

Sì. La funzione 'Ultimo' è il wrapper del ciclo. Nessuna magia all'interno –

risposta

11

Hai ragione, se si dà un'occhiata al codice come implementare Last (da Reflector):

public static TSource Last<TSource>(this IEnumerable<TSource> source) 
{ 
    if (source == null) 
    { 
     throw Error.ArgumentNull("source"); 
    } 
    IList<TSource> list = source as IList<TSource>; 
    if (list != null) 
    { 
     int count = list.Count; 
     if (count > 0) 
     { 
      return list[count - 1]; 
     } 
    } 
    else 
    { 
     using (IEnumerator<TSource> enumerator = source.GetEnumerator()) 
     { 
      if (enumerator.MoveNext()) 
      { 
       TSource current; 
       do 
       { 
        current = enumerator.Current; 
       } 
       while (enumerator.MoveNext()); 
       return current; 
      } 
     } 
    } 
    throw Error.NoElements(); 
} 

Ottimizza in realtà per List<T> restituendo list[count - 1];

+0

E anche se non è stato ottimizzato in questo codice, il compilatore JIT potrebbe potenzialmente ottimizzare la chiamata se avesse abbastanza informazioni. –

+0

E 'interessante, per me, non è stato ottimizzato per 'ICollection .Count' (dato' IList : ICollection '). cose che ti fanno andare Hmm. –

+0

+1. Potete per favore mostrare il link per il codice sopra? –

Problemi correlati