我在 C# 中有以下结构来表示图形边缘:
struct Edge
{
public Edge(int leftA, int leftB, int leftC, int leftD, int rightA, int rightB, int rightC, int rightD)
{
LeftIdA = leftA;
LeftIdB = leftB;
LeftIdC = leftC;
LeftIdD = leftD;
RightIdA = rightA;
RightIdB = rightB;
RightIdC = rightC;
RightIdD = rightD;
}
public readonly int LeftIdA;
public readonly int LeftIdB;
public readonly int LeftIdC;
public readonly int LeftIdD;
public readonly int RightIdA;
public readonly int RightIdB;
public readonly int RightIdC;
public readonly int RightIdD;
}
并且需要在 HashSet 中存储很多(大约 500 万),所以没有重复。GetHashCode 的一个好的实现是什么,所以它针对速度进行了优化?
我试图将每个 id 的 4 位存储在返回的整数中,如下所示:
public override int GetHashCode()
{
int A = LeftIdA & 0xF;
int B = LeftIdB & 0xF;
int C = LeftIdC & 0xF;
int D = LeftIdD & 0xF;
int E = RightIdA & 0xF;
int F = RightIdB & 0xF;
int G = RightIdC & 0xF;
int H = RightIdD & 0xF;
int result = A;
result = (result << 4) | B;
result = (result << 4) | C;
result = (result << 4) | D;
result = (result << 4) | E;
result = (result << 4) | F;
result = (result << 4) | G;
result = (result << 4) | H;
return result;
}
但这比将项目添加到列表中要慢 80%。