我有这样一个场景,在这个场景中,内存节约是最重要的。我正在尝试将大于1 GB的肽序列读入内存,并将共享相同序列的肽实例分组在一起。我将多肽对象存储在Hash中,以便快速检查重复项,但发现您无法访问Set中的对象,即使知道Set中包含该对象。
内存真的很重要,如果可能的话,我不想复制数据。(否则我会将我的数据结构设计为:肽= Dictionary<string, Peptide>,但这将复制字典和肽类中的字符串)。下面的代码向您展示了我想要完成的任务:
public SomeClass {
// Main Storage of all the Peptide instances, class provided below
private HashSet<Peptide> peptides = new HashSet<Peptide>();
public void SomeMethod(IEnumerable<string> files) {
foreach(string file in files) {
using(PeptideReader reader = new PeptideReader(file)) {
foreach(DataLine line in reader.ReadNextLine()) {
Peptide testPep = new Peptide(line.Sequence);
if(peptides.Contains(testPep)) {
// ** Problem Is Here **
// I want to get the Peptide object that is in HashSet
// so I can add the DataLine to it, I don't want use the
// testPep object (even though they are considered "equal")
peptides[testPep].Add(line); // I know this doesn't work
testPep.Add(line) // THIS IS NO GOOD, since it won't be saved in the HashSet which i use in other methods.
} else {
// The HashSet doesn't contain this peptide, so we can just add it
testPep.Add(line);
peptides.Add(testPep);
}
}
}
}
}
}
public Peptide : IEquatable<Peptide> {
public string Sequence {get;private set;}
private int hCode = 0;
public PsmList PSMs {get;set;}
public Peptide(string sequence) {
Sequence = sequence.Replace('I', 'L');
hCode = Sequence.GetHashCode();
}
public void Add(DataLine data) {
if(PSMs == null) {
PSMs = new PsmList();
}
PSMs.Add(data);
}
public override int GethashCode() {
return hCode;
}
public bool Equals(Peptide other) {
return Sequence.Equals(other.Sequence);
}
}
public PSMlist : List<DataLine> { // and some other stuff that is not important }为什么HashSet不让我获取包含在HashSet中的对象引用?我知道人们会试图说,如果HashSet.Contains()返回true,那么你的对象是等价的。它们在值方面可能是等价的,但我需要引用是相同的,因为我在多肽类中存储了额外的信息。
我想出的唯一解决方案是Dictionary<Peptide, Peptide>,其中键和值都指向相同的引用。但这看起来有点俗气。有没有其他的数据结构可以做到这一点?
发布于 2011-09-03 08:48:51
基本上,您可以自己重新实现HashSet<T>,但这是我所知道的唯一解决方案。不过,Dictionary<Peptide, Peptide>或Dictionary<string, Peptide>解决方案可能并不是那么低效-如果每个条目只浪费一个引用,我想这将是相对微不足道的。
事实上,如果您从Peptide中删除hCode成员,那么每个对象将节省4个字节,这与x86中的引用大小相同……据我所知,缓存散列是没有意义的,因为您将只计算每个对象的散列一次,至少在您所显示的代码中是这样。
如果你真的非常需要内存,我怀疑你可以比string更有效地存储序列。如果你给我们更多关于序列包含的信息,我们可能会在那里提出一些建议。
我不知道为什么HashSet不允许这样做,除了这是一个相对罕见的要求之外,我不知道有什么特别有力的理由,但我也看到在Java语言中也有这样的要求。
发布于 2011-09-03 08:48:22
使用Dictionary<string, Peptide>。
https://stackoverflow.com/questions/7290443
复制相似问题