C#编码过程中的良好习惯影响性能

本文摘自论坛:http://topic.csdn.net/u/20120706/16/CEB33682-FF71-402C-9FE9-580F5ECFDFC1.html


1.关于for和foreach,尽量使用for,for的写发尽量使用:for (int i = 0, h = arr.Count; i < h; i++)

            List<int> arr = new List<int>();
            for (int i = 0; i < tnum; i++)
                arr.Add(i);
  

            Stopwatch watch = new Stopwatch();
            
            for (int i = 0, h = arr.Count; i < h; i++)
            {
            }
            watch.Stop();
            Console.WriteLine("for1耗时:" + watch.ElapsedTicks.ToString());

            watch.Reset();
            watch.Start();

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

            watch.Reset();
            watch.Start();

            foreach (int str in arr)
            { 
            }

            watch.Stop();
            Console.WriteLine("foreach耗时:" + watch.ElapsedTicks.ToString());
3种写法分别耗时:



2. 字符串拼接:

string a = "aa" + 123.ToString();

而不是用string a = "aa" + 123

3.字符串比较或查找:

  str.IndexOf("abc", StringComparison.Ordinal)

而不是使用:str.IndexOf("abc"),这个等于str.IndexOf(value,StringComparison.CurrentCulture)

StringComparison.CurrentCulture:使用区域敏感排序规则和当前区域比较字符串
StringComparison.Ordinal:使用序号排序规则比较字符串

4. 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[]是调用同一个方法的


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值