Skip to content

Commit 0d6e323

Browse files
MichalPetrykaRevenantX
authored andcommitted
Simplify and optimize type hash (#457)
1 parent a327ccb commit 0d6e323

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

LiteNetLib/Utils/NetPacketProcessor.cs

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,20 @@ public class NetPacketProcessor
77
{
88
private static class HashCache<T>
99
{
10-
public static bool Initialized;
11-
public static ulong Id;
10+
public static readonly ulong Id;
11+
12+
//FNV-1 64 bit hash
13+
static HashCache()
14+
{
15+
ulong hash = 14695981039346656037UL; //offset
16+
string typeName = typeof(T).FullName;
17+
for (var i = 0; i < typeName.Length; i++)
18+
{
19+
hash ^= typeName[i];
20+
hash *= 1099511628211UL; //prime
21+
}
22+
Id = hash;
23+
}
1224
}
1325

1426
protected delegate void SubscribeDelegate(NetDataReader reader, object userData);
@@ -26,22 +38,9 @@ public NetPacketProcessor(int maxStringLength)
2638
_netSerializer = new NetSerializer(maxStringLength);
2739
}
2840

29-
//FNV-1 64 bit hash
3041
protected virtual ulong GetHash<T>()
3142
{
32-
if(HashCache<T>.Initialized)
33-
return HashCache<T>.Id;
34-
35-
ulong hash = 14695981039346656037UL; //offset
36-
string typeName = typeof(T).FullName;
37-
for (var i = 0; i < typeName.Length; i++)
38-
{
39-
hash = hash ^ typeName[i];
40-
hash *= 1099511628211UL; //prime
41-
}
42-
HashCache<T>.Initialized = true;
43-
HashCache<T>.Id = hash;
44-
return hash;
43+
return HashCache<T>.Id;
4544
}
4645

4746
protected virtual SubscribeDelegate GetCallbackFromData(NetDataReader reader)

0 commit comments

Comments
 (0)