首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么ImmutableArray.Create要复制现有的不可变数组?

为什么ImmutableArray.Create要复制现有的不可变数组?
EN

Stack Overflow用户
提问于 2017-10-19 13:50:19
回答 1查看 669关注 0票数 6

我试图在一种方法中将现有的ImmutableArray<T>切片,并认为我可以使用构造方法Create<T>(ImmutableArray<T> a, int offset, int count),如下所示:

代码语言:javascript
复制
 var arr = ImmutableArray.Create('A', 'B', 'C', 'D');
 var bc ImmutableArray.Create(arr, 1, 2); 

我希望我的两个ImmutableArrays能够在这里共享底层数组。但是,当再次检查时,我发现实现没有:

2017年3月18日15757a8离开共折射/./ImmutableArray.cs在github

代码语言:javascript
复制
    /// <summary>
    /// Initializes a new instance of the <see cref="ImmutableArray{T}"/> struct.
    /// </summary>
    /// <param name="items">The array to initialize the array with.
    /// The selected array segment may be copied into a new array.</param>
    /// <param name="start">The index of the first element in the source array to include in the resulting array.</param>
    /// <param name="length">The number of elements from the source array to include in the resulting array.</param>
    /// <remarks>
    /// This overload allows helper methods or custom builder classes to efficiently avoid paying a redundant
    /// tax for copying an array when the new array is a segment of an existing array.
    /// </remarks>
    [Pure]
    public static ImmutableArray<T> Create<T>(ImmutableArray<T> items, int start, int length)
    {
        Requires.Range(start >= 0 && start <= items.Length, nameof(start));
        Requires.Range(length >= 0 && start + length <= items.Length, nameof(length));

        if (length == 0)
        {
            return Create<T>();
        }

        if (start == 0 && length == items.Length)
        {
            return items;
        }

        var array = new T[length];
        Array.Copy(items.array, start, array, 0, length);
        return new ImmutableArray<T>(array);
    }

它为什么要在这里复制底层的项目?这种方法的文档不是误导/错误的吗?上面写着

这种重载允许助手方法或自定义构建器类有效地避免在新数组是现有数组的一部分时为复制数组而支付冗余税。

但是段的情况正好是它复制的时间,而且只有当所需的切片为空或整个输入数组时,它才能避免复制。

除了实现某种ImmutableArraySpan之外,还有其他方法来实现我想要的吗?

EN

回答 1

Stack Overflow用户

发布于 2017-10-19 21:32:24

我将通过以下评论回答我自己的问题:

ImmutableArray不能表示底层数组的一部分,因为它没有相应的字段--显然,添加很少使用的64/128位范围字段太浪费了。

因此,唯一的可能是有一个适当的片/跨结构,目前除了ArraySegment (它不能使用ImmutableArray作为支持数据)之外,没有其他的结构。

编写ImmutableArraySegment、实现IReadOnlyList<T>等可能很容易,因此可能是这里的解决方案。

关于文档--它是尽可能正确的,它避免了它可以复制的几个副本(全部,没有),或者其他的副本。

有一些新的API带有新的Span和ReadonlySpan类型,这些API将附带用于低级别代码(ref返回/局部变量)的神奇语言和运行时特性,.The类型实际上已经作为System.Memory nuget包的一部分发布了,但是在集成它们之前,将无法使用它们来解决在ImmutableArray上需要这种方法的ImmutableArray切片问题(在System.Collections.Immutable中,还不依赖于System.Memory类型)。

代码语言:javascript
复制
public ReadonlySpan<T> Slice(int start, int count)

我猜想/希望这类API一旦建立起来就会出现。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46831531

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档