是否可以在不复制C#8中的元素的情况下遍历结构数组?

Ray*_*Ray 5 c# ref c#-8.0

借助C#8中新的只读实例成员功能,我尝试减少代码中结构实例的不必要复制。

我确实foreach对结构数组进行了一些迭代,根据此答案,这意味着在数组上进行迭代时将复制每个元素。

我以为我现在可以直接修改代码以防止复制,就像这样:

// Example struct, real structs may be even bigger than 32 bytes.
struct Color
{
    public int R;
    public int G;
    public int B;
    public int A;
}

class Program
{
    static void Main()
    {
        Color[] colors = new Color[128];
        foreach (ref readonly Color color in ref colors) // note 'ref readonly' placed here
            Debug.WriteLine($"Color is {color.R} {color.G} {color.B} {color.A}.");
    }
}
Run Code Online (Sandbox Code Playgroud)

可悲的是,这与

CS1510  A ref or out value must be an assignable variable
Run Code Online (Sandbox Code Playgroud)

但是,使用像这样的索引器进行编译:

CS1510  A ref or out value must be an assignable variable
Run Code Online (Sandbox Code Playgroud)

我的foreach替代语法是否错误,还是在C#8中根本不可能(可能是由于内部枚举的实现方式)?还是C#8现在正在应用某些智能并且不再单独复制Color实例?

Als*_*ein 5

foreach基于目标类型的定义而不是一些内部黑匣子工作。我们可以利用它来创建 by-ref 枚举支持:

//using System;

public readonly struct ArrayEnumerableByRef<T>
{
    private readonly T[] _target;

    public ArrayEnumerableByRef(T[] target) => _target = target;

    public Enumerator GetEnumerator() => new Enumerator(_target);

    public struct Enumerator
    {
        private readonly T[] _target;

        private int _index;

        public Enumerator(T[] target)
        {
            _target = target;
            _index = -1;
        }

        public readonly ref T Current
        {
            get
            {
                if (_target is null || _index < 0 || _index > _target.Length)
                {
                    throw new InvalidOperationException();
                }
                return ref _target[_index];
            }
        }

        public bool MoveNext() => ++_index < _target.Length;

        public void Reset() => _index = -1;
    }
}

public static class ArrayExtensions
{
    public static ArrayEnumerableByRef<T> ToEnumerableByRef<T>(this T[] array) => new ArrayEnumerableByRef<T>(array);
}

Run Code Online (Sandbox Code Playgroud)

然后我们可以foreach通过引用枚举一个带循环的数组:

static void Main()
{
    var colors = new Color[128];

    foreach (ref readonly var color in colors.ToEnumerableByRef())
    {
        Debug.WriteLine($"Color is {color.R} {color.G} {color.B} {color.A}.");
    }
}
Run Code Online (Sandbox Code Playgroud)


Ray*_*Ray 5

受到 Alsein 答案的启发,我意识到我可以简单地使用扩展方法(在命名空间中可用)检索Span数组的a ,并使用引用枚举它的跨度功能:AsSpan()System

static void Main()
{
    Color[] colors = new Color[128];
    foreach (ref readonly Color color in colors.AsSpan())
        Debug.WriteLine($"Color is {color.R} {color.G} {color.B} {color.A}.");
}
Run Code Online (Sandbox Code Playgroud)

请记住,这仅适用于数组,不适用于List<T>实例,我还没有找到用于引用枚举结构列表的简单解决方案。

我担心性能,因此我通过以下方式测量了迭代 10 到 1000 个实例所需的时间:Color

  • for与复印
  • forref readonly
  • for复制并缓存数组长度
  • forref readonly缓存数组长度
  • foreach与复印
  • foreachref readonlyAsSpan()

ref foreach并且foreach似乎表现最好(即使在更长的 10000 个实例运行中):

|            Method | ColorCount |        Mean |      Error |     StdDev | Rank |
|------------------ |----------- |------------:|-----------:|-----------:|-----:|
|               For |         10 |    76.76 ns |  0.3310 ns |  0.3096 ns |    4 |
|            ForRef |         10 |    77.31 ns |  0.4397 ns |  0.3898 ns |    4 |
|    ForCacheLength |         10 |    69.39 ns |  0.1923 ns |  0.1605 ns |    3 |
| ForCacheLengthRef |         10 |    69.46 ns |  0.4859 ns |  0.4545 ns |    3 |
|           ForEach |         10 |    68.28 ns |  0.7367 ns |  0.6152 ns |    2 |
|        ForEachRef |         10 |    64.76 ns |  0.6355 ns |  0.5944 ns |    1 |
|               For |       1000 | 6,912.80 ns | 49.9517 ns | 44.2808 ns |    7 |
|            ForRef |       1000 | 6,882.85 ns | 44.9467 ns | 39.8441 ns |    7 |
|    ForCacheLength |       1000 | 6,874.55 ns | 59.6360 ns | 55.7835 ns |    7 |
| ForCacheLengthRef |       1000 | 6,871.79 ns | 42.3081 ns | 39.5750 ns |    7 |
|           ForEach |       1000 | 6,701.68 ns | 31.3103 ns | 27.7558 ns |    6 |
|        ForEachRef |       1000 | 6,341.90 ns | 80.8536 ns | 75.6305 ns |    5 |
Run Code Online (Sandbox Code Playgroud)