6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

new byte[]が許されるのは...

Last updated at Posted at 2020-04-17

.net Core 3.1 の C#で byte[]をnewする話。

将来的に何度も検索しそうなのでこちらに抜粋

元記事: LitJWTに見るモダンなC#のbyte[]とSpan操作法

ようするに、今どきnew byte[]なんてしたら殺されるぞ!

とのこと。

C# 7.2からSpan構造体というのが使えるようになったので
unsafe なしで stackalloc を使えるようになりました。

だから new byte[] が許されるのはC#7.2未満というお話

従来の書き方
var bytes = new byte[Base64.GetMaxBase64UrlDecodeLength(header.Length)];
(データが)あんまり大きくないのが確定してる場合
Span<byte> bytes = stackalloc byte[Base64.GetMaxBase64UrlDecodeLength(header.Length)];

(stackalloc はスタックメモリ(容量はかなり少ない)を使うので、配列の長さが短いもの限定で)

(データが)そこそこ大きいのが来る可能性がある場合
var rentBytes = ArrayPool<byte>.Shared.Rent(Base64.GetMaxBase64UrlDecodeLength(payload.Length));
try
{
    Span<byte> bytes = rentBytes.AsSpan();
     // ....
}
finally
{
    ArrayPool<byte>.Shared.Return(rentBytes);
}

(bytesにデータを流し込んだ後は、.Sliceできちんとサイズ指定して取得します)

(その他参考にさせていただいた記事)

.NET Core 3.0時代のメモリ管理
Spanを使うべき5つの理由
C# - Span のすべて: .NET の新しい頼みの綱を探索する
ReadOnlySequenceについて

6
6
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?