MirrorNetworking / Mirror

#1 Open Source Unity Networking Library
https://mirror-networking.com
MIT License
5.25k stars 775 forks source link

Perf: Rpc overhead #3925

Open miwarnec opened 1 month ago

miwarnec commented 1 month ago

Currently this is how RPCs are serialized and sent:

// server call:
RpcOnFire(42);

// RpcOnFire:
[ClientRpc]
void RpcOnFire(int value)
{
    NetworkWriterPooled writer = NetworkWriterPool.Get();                       // GET WRITER
    writer.WriteVarInt(value);                                                  // WRITE
    SendRPCInternal("RpcOnFire", -1182161215, writer, 0, includeOwner: true);
    NetworkWriterPool.Return(writer);
}

void SendRpcInternal()
{
    RpcMessage message = new RpcMessage
    {
        netId = netId,
        componentIndex = ComponentIndex,
        functionHash = (ushort)functionHashCode,
        payload = writer.ToArraySegment()                                       // ARRAYSEGMENT
    };

    using (NetworkWriterPooled serialized = NetworkWriterPool.Get())            // GET WRITER
    {
        // serialize once
        serialized.Write(message);                                              // WRITE
        // send to all observers
        foreach (NetworkConnectionToClient conn in netIdentity.observers.Values)
            conn.Send(message, channelId);
    }
}

Instead, we could do this:

WriteUInt(netId);
WriteByte(componentIndex)
WriteUShort(functionHash)
Write(serialized parameters) // weaver generated