C#高效编程话题集2

发表于:2012-6-19 09:25

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:Luminji    来源:51Testing软件测试网采编

  第一期话题在: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<len; i++)

     迭代
}

  第二类:

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> list1 = new MyList<int>();
     MyList<int> list2 = new MyList<int>();
     MyList<string> list3 = new MyList<string>();
     Console.WriteLine(MyList<int>.Count);
     Console.WriteLine(MyList<string>.Count);
}
class MyList<T>
{
     public static int Count { get; set; }
     public MyList()
     {
         Count++;
     }

}

  代码输出是莫子?

  只要知道 MyList<int> 和 MyList<string> 是两个不同的类型,这题就不难理解了。.NET 中类型参数不同的封闭泛型类型是不同的类型。

21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号