LoginSignup
3
6

List<T>に対するループを高速にする

Last updated at Posted at 2024-05-07

参考

この記事は、以下の動画を参考にしています。
詳しくは、動画をご覧ください。

CollectionsMarshal.AsSpan

List<T>から、CollectionsMarshal.AsSpanメソッドを使ってSpan<T>を取り出すことができる。
取り出したSpan<T>に対してループすれば、配列T[]に対するループと同程度まで速くなる。

using System.Runtime.InteropServices;

public void Method(List<string> list)
{
    var span = CollectionsMarshal.AsSpan(list);
    foreach (var item in span) // for文でも同程度の効果
    {
        // itemに対する処理
    }
}

(手元の例では、Span<T>に対してループを実行すると、List<T>に比べて実行時間が約半分になりました)

注意

Span<T>を取り出した後に、元のList<T>に対して要素の追加・削除を行わないこと。

3
6
1

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
3
6