ritorno IEnumerable
a meno che non è necessario:
- accesso Conte - per poi tornare
IReadOnlyCollection
.
- modifica elementi e Conteggio è inferiore a ArrayList.Capacity - quindi restituisce matrice.
- aggiungi nuovi elementi - quindi torna all'elenco.
- alcune microottimazioni: fare benchmark. Per esempio. foreach su array è più veloce quindi oltre l'elenco
BenchmarkDotNet = v0.10.8, OS = Windows 10 Redstone 1 (10.0.14393) processore Intel Core i5-2500K = CPU 3.30GHz (Sandy Bridge), ProcessorCount = 4 Frequenza = 3.233.538 Hz, risoluzione = 309.2588 ns, Timer = TSC [host]: Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0 Clr: Clr 4.0.30319.42000, 64bit RyuJIT-v4.6.1648.0 nucleo: NET nucleo 4.6.25211.01, 64bit RyuJIT
Method | Job | Runtime | Mean | Error | StdDev | Min | Max | Median | Rank | Allocated |
---------- |----- |-------- |-----------:|-----------:|----------:|-----------:|-----------:|-----------:|-----:|----------:|
TestList | Clr | Clr | 5,153.3 ns | 34.002 ns | 31.806 ns | 5,119.2 ns | 5,213.4 ns | 5,135.9 ns | 3 | 0 B |
TestArray | Clr | Clr | 730.1 ns | 6.962 ns | 6.512 ns | 722.4 ns | 743.9 ns | 729.5 ns | 2 | 0 B |
TestList | Core | Core | 5,188.4 ns | 102.816 ns | 96.174 ns | 5,070.3 ns | 5,342.6 ns | 5,185.6 ns | 3 | 0 B |
TestArray | Core | Core | 709.0 ns | 6.126 ns | 5.730 ns | 700.8 ns | 718.6 ns | 708.1 ns | 1 | 0 B |
Codice:
[RankColumn, MinColumn, MaxColumn, StdDevColumn, MedianColumn]
[ClrJob, CoreJob]
[HtmlExporter, MarkdownExporter]
[MemoryDiagnoser]
public class BenchmarkForEach
{
List<string> testData = new List<string>();
string[] testArray;
public BenchmarkForEach()
{
for(int i=0;i<1000;i++)
{
testData.Add(i.ToString());
}
testArray = testData.ToArray();
}
[Benchmark]
public int TestList()
{
var x = 0;
foreach(var i in testData)
{
x += i.Length;
}
return x;
}
[Benchmark]
public int TestArray()
{
var x = 0;
foreach (var i in testArray)
{
x += i.Length;
}
return x;
}
}
fonte
2017-07-18 08:30:35
Perché gli array in C# sono malvagi? So che in C/C++ sono malvagie, perché un array e un puntatore sono uguali – user142350
hai visto questo? http://stackoverflow.com/questions/434761/array-versus-listt-when-to-use-which – elan
Odio il termine "X programming construct is evil", usato troppo spesso. Gli array non sono preferiti perché possono essere soggetti a errori con cui lavorare e forniscono meno astrazione tra te e l'implementazione. Onestamente, in C# scompaiono molti dei problemi inerenti agli array C++, ma un IList (o qualche altra raccolta) è un'interfaccia più gradevole e di livello più alto. –