diff options
author | Andrew Arnott <andrewarnott@gmail.com> | 2019-03-08 10:14:09 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-03-08 10:14:09 +0300 |
commit | e2d21dfe4ee9e5f914aa8a3be1a1a73ffd0b7053 (patch) | |
tree | 1a9ddffe83ae666ff93f0a2749c60505a9c084fa | |
parent | 5b0a0e6d6ce3963931b5249cb31ebcee0a084063 (diff) | |
parent | a4196cdfb587e9d9774767e1f2114df82ebeae3a (diff) |
Merge pull request #52 from AArnott/fix50v2.0.49-alpha
Avoid allocating many small arrays while serializing
-rw-r--r-- | src/MessagePack/MemoryPoolWithMinSize.cs | 35 | ||||
-rw-r--r-- | src/MessagePack/MessagePackSerializer.cs | 4 |
2 files changed, 37 insertions, 2 deletions
diff --git a/src/MessagePack/MemoryPoolWithMinSize.cs b/src/MessagePack/MemoryPoolWithMinSize.cs new file mode 100644 index 00000000..dfe08538 --- /dev/null +++ b/src/MessagePack/MemoryPoolWithMinSize.cs @@ -0,0 +1,35 @@ +using System; +using System.Buffers; +using System.Collections.Generic; +using System.Text; + +namespace MessagePack +{ + /// <summary> + /// A wrapper around <see cref="MemoryPool{T}.Shared"/> that ensures we never allocate arrays smaller than 4096. + /// </summary> + internal class MemoryPoolWithMinSize : MemoryPool<byte> + { + /// <summary> + /// The minimum size for an array that we will ever request from the underlying pool. + /// </summary> + private const int MinSize = 4 * 1024; + + internal static readonly MemoryPoolWithMinSize Instance = new MemoryPoolWithMinSize(); + + private MemoryPoolWithMinSize() + { + } + + /// <inheritdoc /> + public override int MaxBufferSize => throw new NotImplementedException(); + + /// <inheritdoc /> + public override IMemoryOwner<byte> Rent(int minBufferSize = -1) => Shared.Rent(Math.Max(MinSize, minBufferSize)); + + /// <inheritdoc /> + protected override void Dispose(bool disposing) + { + } + } +} diff --git a/src/MessagePack/MessagePackSerializer.cs b/src/MessagePack/MessagePackSerializer.cs index 637369e4..4a6ec987 100644 --- a/src/MessagePack/MessagePackSerializer.cs +++ b/src/MessagePack/MessagePackSerializer.cs @@ -79,7 +79,7 @@ namespace MessagePack /// <returns>A byte array with the serialized value.</returns> public byte[] Serialize<T>(T value, IFormatterResolver resolver = null) { - using (var sequence = new Sequence<byte>()) + using (var sequence = new Sequence<byte>(MemoryPoolWithMinSize.Instance)) { this.Serialize(sequence, value, resolver); return sequence.AsReadOnlySequence.ToArray(); @@ -94,7 +94,7 @@ namespace MessagePack /// <param name="resolver">The resolver to use during deserialization. Use <c>null</c> to use the <see cref="DefaultResolver"/>.</param> public void Serialize<T>(Stream stream, T value, IFormatterResolver resolver = null) { - using (var sequence = new Sequence<byte>()) + using (var sequence = new Sequence<byte>(MemoryPoolWithMinSize.Instance)) { this.Serialize<T>(sequence, value, resolver); foreach (var segment in sequence.AsReadOnlySequence) |