第一个问题是关于保护我的列表免受外部更改(删除/添加/清除等)的方式
有我的方式:
class Foo
{
public int[] MyCollection
{
get{ return (_myCollection==null)?null:_myCollection.ToArray();
}
protected List<int> _myCollection;
}
好吗?或者有没有更好的想法,或者可能是模式?
第二:当我用秒表测试这个解决方案时,我很惊讶。
List -enumeration 比 List.ToArray() 枚举慢,有施放时间:
List<int> myList = new List<int>();
for (int j = 0; j < 10000; j++)
{
myList.Add(j);
}
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000; i++)
{
//casting every iteration:
var ROC = myList.ToArray();
int count = 0;
foreach (var a in ROC)
{
count += a;
}
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
它显示了 700 毫秒,并且
List<int> myList = new List<int>();
for (int j = 0; j < 10000; j++)
{
myList.Add(j);
}
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 10000; i++)
{
int count = 0;
//No casting at all
foreach (var a in myList)
{
count += a;
}
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
显示 843 毫秒……为什么会这样?