There can be no Triumph without Loss,No Victory without Suffering,No Freedom without Sacrifice.
All you have to decide is what to do with the time that is given to you.
Get busy Living, or Get busy Dying?
  首页 | 留言给我 | 订阅 Rss | CLI | 黄白之恋 Posts:158   Hits: 5071081    Comments: 173    
 日历归档
<<  <  2024 - 04  >  >>
SuMoTuWeThFrSa
 123456
78910111213
14151617181920
21222324252627
282930
 About Me
 Name: ZhangSichu
 Sex: Male
 Age: 32
 Email: ZhangSichu@gmail.com
 MSN: ZhangSichu@hotmail.com
 Home: ZhangSichu.com
 WeiBo: weibo.com/zhangsichu
 个人推荐
 分类归档
  ·C++/C(5)  RSS
  ·软件工程(1)  RSS
  ·杂事/随感(26)  RSS
  ·.Net/Java(30)  RSS
  ·面向对象程序设计(5)  RSS
  ·汇编/破解(0)  RSS
  ·平面设计(3)  RSS
  ·SQL(5)  RSS
  ·COM/COM+(2)  RSS
  ·Web开发(81)  RSS
 My Friends
Back Forward Refresh Home 2024年4月24日 星期三 RSS CLI Mine Sweeper. In Javascript.

  加速Dictionary取值[转载]
字体大小 [ ]

原文: http://gcdn.grapecity.com/cs/forums/thread/3709.aspx 经过编辑。
在程序中常会有这样的代码。
多了可能会影响效率。
Dictionary<Key, Value> dict = new Dictionary<Key, Value>();
...........

if (dict.ContainsKey(key))
{
Value value = dict[key];
}

看来没有什么问题。
但是在实际项目中,这种代码一般会写在底层的class中。
它被调用的次数相当大时,需要优化。

MS.Net2.0如何实现:
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback
{
public bool ContainsKey(TKey key)
{
return (this.FindEntry(key) >= 0);
}
public TValue this[TKey key]
{
get
{
int index = this.FindEntry(key);
if (index >= 0)
{
return this.entries[index].value;
}
ThrowHelper.ThrowKeyNotFoundException();
return default(TValue);
}
set
{
this.Insert(key, value, false);
}
}
}

FindEntry()被调用了2次!这就导致速度变慢了1倍!

解决方案:估计微软自己也发现了,所以在2.0里面封装了一个新的method:
public bool TryGetValue(TKey key, out TValue value)
{
int index = this.FindEntry(key);
if (index >= 0)
{
value = this.entries[index].value;
return true;
}
value = default(TValue);
return false;
}

于是,上面的代码就可以改写成:
Dictionary<Key, Value> dict = new Dictionary<Key, Value>();
...........
Value value;
if (dict.TryGetValue(key, out value))
{
value.......
}

使用TryGetValue,FindEntry 只调用了一次,同时判断了有没有也得到了值。
  Posted @ 3/15/2007 5:37:45 PM | Hits (48812) | Comments (2

  Comment
 #re:加速Dictionary<TKey, TValue>取值[转载]  12/19/2013 4:39:03 PM  淡淡的地址
顶顶顶顶成v
 #re:加速Dictionary<TKey, TValue>取值[转载]  10/29/2013 5:38:09 PM  123
sf
  Post Comment
标题 *
作者 *
密码 记住我
评论 *
    


Stable in Firefox 1.5 2.0Stable in IE6 IE7Stable in MozillaStable in Netscape
ZhangSichu.com V0.1.7507
Powered By ZhangSichu
Copyright © ZhangSichu
Download ZhangSichu.com source code. Download source code