Search code examples
c#optimizationnetwork-programmingmemory-efficient

C# - Reuse IPEndPoint Object


As part of an educational project, I started to work on highly-optimized MMO game server in C#.

I try to avoid as much as I can from extra memory allocation, and I wanted to ask if it is possible to reuse an IPEndPoint object without allocating memory.

I would expect something like this (the function I want is IPEndPoint.DeepCopy):

public void Send(IPEndPoint toIP, byte[] buffer, int numOfBytes)
    {
        // try aquire send event from free list
        SocketAsyncEventArgs e;
        bool successfullyTaken = this._writeEventArgsPool.TryTake(out e);

        // copy buffer
        // ....

        // set the outgoing IP
        IPEndPoint.DeepCopy(toIP, e.RemoteEndPoint);
        
        // send the packet
        //..
    }

Thanks.


Solution

  • Not possible to avoid allocations from IPEndPoint for now. There's a proposal! but it has not seen much progress. One can fiddle with the SocketAddress serialization using a custom EndPoint for specific usage as done in No-gc-sockets! but there's no guarantee that this strategy will work across .NET implementations. The MutableIPEndPoint in No-gc-sockets for example seems to work fine for .NETFramework 4.7.x but not .NETCore 3.x due to internal implementation details.