CloudStructures icon indicating copy to clipboard operation
CloudStructures copied to clipboard

use Lease APIs to less allocate memory

Open neuecc opened this issue 5 years ago • 0 comments

StachExchange.Redis 2.x has new lease APIs. It can avoid byte[] allocation in deserialize.

using (var lease = conn.GetDatabase().StringGetLease("key"))
{
    return MessagePackSerializer.Deserialize<Foo>(lease.Memory);
}

For serialize, RedisValue accepts ReadOnlyMemory so we can write the following.

public Task<bool> async SetAsync<T>(T value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None)
{
    // ArrayBufferWriter is only for .NET Core 3.0 and it creates new T[]
    // create similar code that uses ArrayPool<byte>.Shared.Rent
    using(var bufferWriter = new ArrayBufferWriter<byte>())
    {
        MessagePackSerializer.Serialize(bufferWriter, value);
        RedisValue serialized = bufferWriter.WrittenMemory;
        return await this.Connection.Database.StringSetAsync(this.Key, serialized, expiry, when, flags);
    }
}

neuecc avatar Dec 18 '19 08:12 neuecc