Small changes (#1714)

- Don't allocate for empty arrays.
- Don't allocate the list of pre-serialized messages until writing
This commit is contained in:
David Fowler 2018-03-25 12:38:51 -07:00 committed by GitHub
parent 733a3b3c2d
commit 65204ec6f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 8 deletions

View File

@ -12,9 +12,8 @@ namespace Microsoft.AspNetCore.SignalR.Internal.Protocol
{
}
// Initialize with capacity 2 for the 2 built in protocols
private object _lock = new object();
private readonly List<SerializedMessage> _serializedMessages = new List<SerializedMessage>(2);
private List<SerializedMessage> _serializedMessages;
public byte[] WriteMessage(IHubProtocol protocol)
{
@ -25,7 +24,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal.Protocol
lock (_lock)
{
for (var i = 0; i < _serializedMessages.Count; i++)
for (var i = 0; i < _serializedMessages?.Count; i++)
{
if (_serializedMessages[i].Protocol.Equals(protocol))
{
@ -35,6 +34,12 @@ namespace Microsoft.AspNetCore.SignalR.Internal.Protocol
var bytes = protocol.WriteToArray(this);
if (_serializedMessages == null)
{
// Initialize with capacity 2 for the 2 built in protocols
_serializedMessages = new List<SerializedMessage>(2);
}
// We don't want to balloon memory if someone writes a poor IHubProtocolResolver
// So we cap how many caches we store and worst case just serialize the message for every connection
if (_serializedMessages.Count < 10)

View File

@ -559,7 +559,7 @@ namespace Microsoft.AspNetCore.SignalR.Internal.Protocol
private object[] BindArguments(JsonTextReader reader, IReadOnlyList<Type> paramTypes)
{
var arguments = new object[paramTypes.Count];
object[] arguments = null;
var paramIndex = 0;
var argumentsCount = 0;
@ -572,7 +572,12 @@ namespace Microsoft.AspNetCore.SignalR.Internal.Protocol
throw new InvalidDataException($"Invocation provides {argumentsCount} argument(s) but target expects {paramTypes.Count}.");
}
return arguments;
return arguments ?? Array.Empty<object>();
}
if (arguments == null)
{
arguments = new object[paramTypes.Count];
}
try
@ -608,12 +613,18 @@ namespace Microsoft.AspNetCore.SignalR.Internal.Protocol
private object[] BindArguments(JArray args, IReadOnlyList<Type> paramTypes)
{
var arguments = new object[args.Count];
if (paramTypes.Count != arguments.Length)
if (paramTypes.Count != args.Count)
{
throw new InvalidDataException($"Invocation provides {arguments.Length} argument(s) but target expects {paramTypes.Count}.");
throw new InvalidDataException($"Invocation provides {args.Count} argument(s) but target expects {paramTypes.Count}.");
}
if (paramTypes.Count == 0)
{
return Array.Empty<object>();
}
var arguments = new object[args.Count];
try
{
for (var i = 0; i < paramTypes.Count; i++)