Skip to content

Commit

Permalink
perf: removing allocations from SendToMany
Browse files Browse the repository at this point in the history
  • Loading branch information
James-Frowen committed Jul 20, 2021
1 parent 2f4112c commit c57f64d
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions Assets/Mirage/Runtime/NetworkServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,13 @@ public void SendToAll<T>(T msg, int channelId = Channel.Reliable)
SendToMany(Players, msg, channelId);
}

/// <summary>
/// Sends a message to many connections
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="players"></param>
/// <param name="msg"></param>
/// <param name="channelId"></param>
public static void SendToMany<T>(IEnumerable<INetworkPlayer> players, T msg, int channelId = Channel.Reliable)
{
using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
Expand All @@ -420,6 +427,33 @@ public static void SendToMany<T>(IEnumerable<INetworkPlayer> players, T msg, int
}
}

/// <summary>
/// Sends a message to many connections
/// <para>
/// Same as <see cref="SendToMany{T}(IEnumerable{INetworkPlayer}, T, int)"/> but uses for loop to avoid allocations
/// </para>
/// </summary>
/// <remarks>
/// Using list in foreach loop causes Unity's mono version to box the struct which causes allocations, <see href="https://docs.unity3d.com/2019.4/Documentation/Manual/BestPracticeUnderstandingPerformanceInUnity4-1.html">Understanding the managed heap</see>
/// </remarks>
public static void SendToMany<T>(IReadOnlyList<INetworkPlayer> players, T msg, int channelId = Channel.Reliable)
{
using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter())
{
// pack message into byte[] once
MessagePacker.Pack(msg, writer);
var segment = writer.ToArraySegment();
int count = players.Count;

for (int i = 0; i < count; i++)
{
players[i].Send(segment, channelId);
}

NetworkDiagnostics.OnSend(msg, segment.Count, count);
}
}

void ConnectionAccepted(INetworkPlayer player)
{
if (logger.LogEnabled()) logger.Log("Server accepted client:" + player);
Expand Down

0 comments on commit c57f64d

Please sign in to comment.