【问题标题】:Can I foreach over an array of structs without copying the elements in C# 8?我可以在不复制 C# 8 中的元素的情况下遍历结构数组吗?
【发布时间】:2020-01-23 22:48:40
【问题描述】:

使用新的readonly instance member features in C# 8,我尝试在我的代码中减少不必要的结构实例复制。

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

我想我现在可以简单地修改我的代码来防止复制,就像这样:

// 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}.");
    }
}

遗憾的是,这不能编译

CS1510  A ref or out value must be an assignable variable

但是,使用这样的索引器可以编译:

static void Main()
{
    Color[] colors = new Color[128];
    for (int i = 0; i < colors.Length; i++)
    {
        ref readonly Color color = ref colors[i];
        Debug.WriteLine($"Color is {color.R} {color.G} {color.B} {color.A}.");
    }
}

我在 foreach 替代方案中的语法是否错误,或者这在 C# 8 中根本不可能(可能是因为枚举是如何在内部实现的)? 还是现在 C# 8 应用了一些智能并且不再自行复制 Color 实例?

【问题讨论】:

  • 这不会使您的问题无效,但是复制实例(只有 4 个字节)实际上比就地使用它(编译器必须担心别名)效率更高。
  • @BenVoigt 这是一个有效的评论,我应该补充一点,这只是愚蠢的示例代码,我的结构可能大于 4 个字节。 - 现在编辑为 32 字节大。
  • 链接的提案是否以任何方式修改了foreach 的行为?我以为这只是关于readonlystructs 的成员
  • 另外基于我(有限的)知识,实现你想要的方法是使用ReadOnlySpan&lt;Color&gt; colors = new Color[128];(它允许你在foreach中使用ref readonly
  • 这里要记住的一点是,foreach 与集合一起工作。它适用于枚举器。 Wich 将从任何现有集合中隐式创建。因此,您将在开始和每次迭代/调用 .next() 时获得所有枚举器开销。通常我只在人们遇到枚举数的“非可变”属性时才提到它。但是对于您的情况,这种性能差异可能很重要并影响更大的问题。

标签: c# ref c#-8.0


【解决方案1】:

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

//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);
}

然后我们可以通过引用枚举一个带有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}.");
    }
}

【讨论】:

  • 不错的解决方案,它让我想到了将数组包装到 Span&lt;Color&gt; 中,它也实现了这个 by-ref 枚举,调用 foreach (ref readonly Color color in colors.AsSpan()) - 基本上它会这样做吗?它似乎可以编译。
  • 它可以编译,但它仍然有点不同,因为Span&lt;T&gt; 是用ref 定义的,这是一个仅堆栈结构,因为Span&lt;T&gt;.Enumerable 也是一个仅堆栈结构,因为它包含对Span&lt;T&gt; 的引用。有limits to stack-only structure
  • 但是如果我没看错的话,为了迭代结构数组而不复制它就足够了?
【解决方案2】:

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

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}.");
}

请记住,这仅适用于数组,不适用于 List&lt;T&gt; 实例,我还没有找到一个简单的解决方案来引用结构列表。

我担心性能问题,所以 I measured the time it takes 以下列方式迭代 10 和 1000 个 Color 实例:

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

ref foreachforeach 似乎表现最好(即使在更长的 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 |

【讨论】:

  • 对于您的最后一句话,请查看BenchmarkDotNet,它以 nuget 包的形式提供。您还应该在不使用 ref 的情况下测量简单的 foreach/for,以便您可以看到使用 ref 确实有帮助。
  • @LasseVågsætherKarlsen 一个了不起的图书馆。我刚刚更新了我的答案以包含非常有趣的结果。
猜你喜欢
  • 2022-12-11
  • 1970-01-01
  • 2021-07-02
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 2021-07-19
相关资源
最近更新 更多