High-Performance Server Blog Post
Profiling a C# game server and improving its performance has been greatly aided by the following blog.
C# High-Performance Server - Memory Fragmentation | leafbird/devnote
In the content of the above article, it mentioned that WeakReference creates memory pinning. However, if memory is pinned, it would mean that the memory referenced by WeakReference is held strongly, which raises the question of whether WeakReference would become meaningless.
`System.WeakReference` also uses pinning handles, which can lead to fragmentation.
WeakReference Does Not Pin Memory
To get straight to the point, WeakReference does not pin memory.
I searched on Google and ChatGPT but couldn't find any information linking WeakReference to pinned handles. So, I decided to follow the blog's suggestion and leave a dump to check the .NET handles.
After creating 10,000 WeakReferences and leaving a dump to check the handles, I found that instead of pinned handles, there were 10,000 Weak Short handles remaining.
For reference, types like Weak Short and Weak Long are used internally in the .NET runtime, which is written in C++. You can find more details in runtime/src/coreclr/gc/gcinterface.h at main · dotnet/runtime · GitHub.
The accessible handle types in .NET are as follows, and WeakReference uses either the Weak or WeakTrackResurrection type depending on the creation options:
public enum GCHandleType
{
Weak,
WeakTrackResurrection,
Normal,
Pinned,
}
In any case, WeakReference does not pin memory, and therefore does not contribute to memory fragmentation.
Of course, there are costs associated with managing the handle table in the .NET runtime and modifying the pointers of handles when the garbage collector runs, so creating too many handles is not advisable.