for的效率测试和结果,分享一下

之前一直认为
for (int i = 0, h = arr.Count; i < h; i++)

for (int i = 0; i < arr.Count; i++)
两种写法,在C#里应该是差不多的,今天突然有人问,就写了个程序测试了一下,结果出乎我的意料
如果arr是List<T>,前者的效率比后者高大约一倍,如果arr是string[],两者效率基本差不多

测试代码:
int tnum = 100000; // 添加或查找的次数
int outnum = 10; // 外层循环次数

List<string> arr = new List<string>();
for(int i=0;i<tnum;i++)
    arr.Add(i.ToString());
string[] arr2 = new string[tnum];

for(int j=0;j<outnum;j++)
{
    Stopwatch watch = new Stopwatch();
    string msg;

    msg = "Number ";
    watch.Reset();
    watch.Start();
    for (int i = 0, h = arr.Count; i < h; i++)
    {
    }
    watch.Stop();
    Console.WriteLine(msg + "耗时:" + watch.ElapsedTicks.ToString());

    msg = ".Count ";
    watch.Reset();
    watch.Start();
    for (int i = 0; i < arr.Count; i++)
    {
    }
    watch.Stop();
    Console.WriteLine(msg + "耗时:" + watch.ElapsedTicks.ToString());

    msg = "Length ";
    watch.Reset();
    watch.Start();
    for (int i = 0; i < arr2.Length; i++)
    {
    }
    watch.Stop();
    Console.WriteLine(msg + "耗时:" + watch.ElapsedTicks.ToString());
}

发这个帖的意思是,要养成良好的代码习惯,
当然,这个不是影响代码性能的重点,只是平时写代码时,顺手就写上效率较高的代码,会更好。

类似的提升效率的地方,还有拼接字符串时,值类型一定要加上ToString()
比如用:string a = "aa" + 123.ToString();
而不是用string a = "aa" + 123

再比如:
字符串比较或查找,请加上StringComparison.Ordinal参数如果要忽略大小写,请使用StringComparison.OrdinalIgnoreCase
比如要使用:str.IndexOf("abc", StringComparison.Ordinal)
而不是使用:str.IndexOf("abc"),这个等于str.IndexOf(value,StringComparison.CurrentCulture)
StringComparison.CurrentCulture:使用区域敏感排序规则和当前区域比较字符串
StringComparison.Ordinal:使用序号排序规则比较字符串

 

再帖一个好习惯:
HashTable、Dictionary、SortedList、SortedDictionary等字典使用 a、使用字典的TryGetValue方法,如:
Dictionary<string, string> abc;
string a;
if(!abc.TryGetValue(key, out a)){
//key不存在
}else{
}
而不要用下面的代码,因为下面的代码重复查找了2次key:
if(!abc.ContainKeys(key))
{
//key不存在
}else{
a = abc[key];
}
b、删除字典的key时,直接使用Remove方法,不要事先判断,比如:
Dictionary<string, string> abc;
if(abc.Remove(key)){// 没必要先判断ContainKeys,重复查找,浪费性能
//key存在,且移除成功
}else{
//key不存在,或移除失败
}
c、插入元素时,直接使用this[key] = value,如:
abc[key] = value;// 注意需求,如果允许覆盖才可以用
而不需要:if(!abc.ContainsKey(key))abc.Add(key, value);
反编译代码,可以看到Add和this[]是调用同一个方法的

 

转自:http://topic.csdn.net/u/20120706/16/ceb33682-ff71-402c-9fe9-580f5ecfdfc1.html

 
posted @ 2012-07-11 23:24  Arthur.Wang  阅读(852)  评论(4编辑  收藏  举报