我需要通过两个整数键来超快速地存储和检索值。
所以我有输入值uint Id1, uint Id2
并且需要得到uint Count
.
Id1
我也知道和的最大值Id2
(大约是 5 000 000)。
我当前的实现需要大约 70% 的应用程序工作时间,并且可能需要几天时间。
它只使用标准的.net 字典,当然可以改进。但我想这是计算机科学中非常有用的操作,毫无疑问存在更有效的算法。
这是我的实现
void Main()
{
var rep = new Repository();
var sw = new Stopwatch();
sw.Start();
for (uint i = 0; i < 10000; i++)
{
for (uint j = 0; j < 1000; j++)
{
rep.Add(new DomainEntity(){Id1 = i, Id2 = j, Count = 1});
}
}
for (uint i = 0; i < 10000; i++)
{
for (uint j = 0; j < 1000; j++)
{
rep.GetDomainEntityByIds(i,j);
}
}
sw.Stop();
Console.WriteLine ("Elapsed:{0}", sw.Elapsed);
}
public class Repository
{
private readonly Dictionary<Tuple<UInt32, UInt32>, UInt32> _dictStore;
public Repository()
{
_dictStore = new Dictionary<Tuple<uint, uint>, uint>();
}
public uint Add(DomainEntity item)
{
var entry = MapToTableEntry(item);
_dictStore.Add(entry.Key,entry.Value);
return 0;
}
public void Update(DomainEntity item)
{
var entry = MapToTableEntry(item);
_dictStore[entry.Key] = entry.Value;
}
public IEnumerable<DomainEntity> GetAllItems()
{
return _dictStore.Select(MapToDomainEntity);
}
public DomainEntity GetDomainEntityByIds(uint articleId1, uint articleId2)
{
var tuple = new Tuple<uint, uint>(articleId1, articleId2);
if (_dictStore.ContainsKey(tuple))
{
return MapToDomainEntity(new KeyValuePair<Tuple<uint, uint>, uint>(tuple, _dictStore[tuple]));
}
return null;
}
private KeyValuePair<Tuple<uint, uint>, uint> MapToTableEntry(DomainEntity item)
{
return new KeyValuePair<Tuple<uint, uint>, uint>(new Tuple<uint, uint>(item.Id1,item.Id2), item.Count);
}
private DomainEntity MapToDomainEntity(KeyValuePair<Tuple<uint, uint>, uint> entry)
{
return new DomainEntity
{
Id1 = entry.Key.Item1,
Id2 = entry.Key.Item2,
Count = entry.Value,
};
}
}
public class DomainEntity
{
public uint Id1 { get; set; }
public uint Id2 { get; set; }
public uint Count { get; set; }
}