| 发表于:2007-09-18 15:49:4210楼 得分:100 |
list <string> stringcollection = new list <string> (); int addstring1(string st) { int tmp = stringcollection.indexof(st); if (tmp > -1) return tmp; stringcollection.add(st); return stringcollection.count - 1; } sortedlist <string, int> sortedlist = new sortedlist <string, int> (); int addstring2(string st) { int tmp = sortedlist.indexofkey(st); if (tmp > -1) return sortedlist.values[tmp]; sortedlist.add(st, stringcollection.count); stringcollection.add(st); return stringcollection.count - 1; } private void button1_click(object sender, eventargs e) { random vrandom = new random(10010); // 保证随机数相同 stringcollection.clear(); int vtickcount = environment.tickcount; for (int i = 0; i < 100000; i++) { addstring1(vrandom.next(10000).tostring()); } console.writeline( "100000次addstring1()消耗{0} 个数:{1} ", environment.tickcount - vtickcount, stringcollection.count); vrandom = new random(10010); // 保证随机数相同 stringcollection.clear(); sortedlist.clear(); // 清除字典数据 vtickcount = environment.tickcount; for (int i = 0; i < 100000; i++) { addstring2(vrandom.next(10000).tostring()); } console.writeline( "100000次addstring2()消耗{0} 个数:{1} ", environment.tickcount - vtickcount, stringcollection.count); } 结果 100000次addstring1()消耗16266 个数:9999 100000次addstring2()消耗641 个数:9999 用空间换时间 用一个排序的列表充当索引 | | |
|