第一期话题在:C#高效编程话题集1
1:确保集合的线程安全
如果使用.net4.0,有新的线程安全集合类
新的 System.Collections.Concurrent 命名空间引入了多个新的线程安全集合类,可在需要时随时提供对项的无锁访问,并在锁适用时提供细粒度锁定。 在多线程方案中使用这些类应获得优于集合类型(例如, ArrayList 和 List <(Of <(T >)>))的性能。
除了System.Collections.Concurrent空间下集合外,非泛型集合使用lock(非泛型集合对象.SyncRoot)进行锁定达到集合线程安全目的
泛型集合使用
static object sycObj = new object(); //是否static看具体应用 lock (sycObj) { //操作集合。 } |
2:循环中先求长度还是使用list.Count,哪个效率高
第一类:
int len = list.Count; |
第二类:
for(int i; i<list.Count; i++) |
答案是一样高。
第一种方法完全没有必要,很多人可能以为那样会为代码带来效率,而实际上是不会给效率带来任何提升。
因为事实上,索引器内部,为了安全期间,还是会去求整个list的count的。将两者代码贴出来可能会更好的理解这一点:
public T this[int index] { get { if (index >= this._size) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return this._items[index]; } set { if (index >= this._size) { ThrowHelper.ThrowArgumentOutOfRangeException(); } this._items[index] = value; this._version++; } } |
public int Count { get { return this._size; } } |
3:善用延迟求值
以List<int> list = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};为例,说明linq查询中的延迟求值和主动求值。
List<int> list = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var temp1 = from c in list where c > 5 select c; var temp2 = (from c in list where c > 5 select c).ToList<int>(); list[0] = 11; Console.Write("temp1: "); foreach (var item in temp1) { Console.Write(item.ToString() + " "); } Console.Write("\ntemp2: "); foreach (var item in temp2) { Console.Write(item.ToString() + " "); } |
4:谨慎泛型类型中的静态成员
static void Main(string[] args) } |
代码输出是莫子?
只要知道 MyList<int> 和 MyList<string> 是两个不同的类型,这题就不难理解了。.NET 中类型参数不同的封闭泛型类型是不同的类型。