Skip to content

Commit

Permalink
remove unnecessary allocs in SideChannelMananger (#4886)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris Elion authored Jan 27, 2021
1 parent 4cb9384 commit 0e573a1
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions com.unity.ml-agents/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ removed when training with a player. The Editor still requires it to be clamped
#### com.unity.ml-agents (C#)
- Fix a compile warning about using an obsolete enum in `GrpcExtensions.cs`. (#4812)
- CameraSensor now logs an error if the GraphicsDevice is null. (#4880)
- Removed unnecessary memory allocations in `ActuatorManager.UpdateActionArray()` (#4877)
- Removed unnecessary memory allocations in `SensorShapeValidator.ValidateSensors()` (#4879)
- Removed unnecessary memory allocations in `SideChannelManager.GetSideChannelMessage()` (#4886)
- Removed several memory allocations that happened during inference. On a test scene, this
reduced the amount of memory allocated by approximately 25%. (#4887)

Expand Down
26 changes: 26 additions & 0 deletions com.unity.ml-agents/Runtime/SideChannels/SideChannelManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,13 @@ internal static byte[] GetSideChannelMessage()
/// <returns></returns>
internal static byte[] GetSideChannelMessage(Dictionary<Guid, SideChannel> sideChannels)
{
if (!HasOutgoingMessages(sideChannels))
{
// Early out so that we don't create the MemoryStream or BinaryWriter.
// This is the most common case.
return Array.Empty<byte>();
}

using (var memStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(memStream))
Expand All @@ -140,6 +147,25 @@ internal static byte[] GetSideChannelMessage(Dictionary<Guid, SideChannel> sideC
}
}

/// <summary>
/// Check whether any of the sidechannels have queued messages.
/// </summary>
/// <param name="sideChannels"></param>
/// <returns></returns>
static bool HasOutgoingMessages(Dictionary<Guid, SideChannel> sideChannels)
{
foreach (var sideChannel in sideChannels.Values)
{
var messageList = sideChannel.MessageQueue;
if (messageList.Count > 0)
{
return true;
}
}

return false;
}

/// <summary>
/// Separates the data received from Python into individual messages for each registered side channel.
/// </summary>
Expand Down

0 comments on commit 0e573a1

Please sign in to comment.