Utf8文字列のリテラルについて

https://github.com/dotnet/csharplang/blob/main/proposals/utf8-string-literals.md

ここに書いてあるのを機械翻訳で読んだのですが、とてもためになりました。

// Efficient but verbose and error prone
static ReadOnlySpan<byte> AuthWithTrailingSpace => new byte[] { 0x41, 0x55, 0x54, 0x48, 0x20 };
WriteBytes(AuthWithTrailingSpace);

byte[]から、ReadOnlySpanで返す
これは最適化が入っているみたいで、実際にはbyte[]が作られず、プログラムを直接参照するとのことで、すごく無駄が無い。

// Incurs allocation and startup costs performing an encoding that could have been done at compile-time
static readonly byte[] s_authWithTrailingSpace = Encoding.UTF8.GetBytes("AUTH ");
WriteBytes(s_authWithTrailingSpace);

stringから、byte[]に変えて、staticでキャッシュしておく。
実行時の速度は速い。おそらくキャッシュサイズ分メモリを消費しているはずなので、その分は不利だと思われる。
ただ、Benchmarkでも比較してみたのだけど、Benchmarkでは差は出なかった。

// Simplest / most convenient but terribly inefficient
WriteBytes(Encoding.UTF8.GetBytes("AUTH "));

1行で書けるけど、都度変換が発生するから遅い。
現状では、この使い分けってことですね。

将来に入る、utf8リテラルに期待したいですね。

投稿日:
カテゴリー: C#

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です