【发布时间】:2018-07-12 07:49:05
【问题描述】:
有没有什么方法(可能是一个肮脏的hack)来创建一个只使用指定数组而不是复制它的 ImmutableArray?
我有一个我知道不会更改的数组,我想创建一个 ImmutableArray 以允许客户端安全地访问我的数组。
看source code for ImmutableArray,我看Create方法也无济于事:
public static ImmutableArray<T> Create<T>(params T[] items)
{
if (items == null)
{
return Create<T>();
}
// We can't trust that the array passed in will never be mutated by the caller.
// The caller may have passed in an array explicitly (not relying on compiler params keyword)
// and could then change the array after the call, thereby violating the immutable
// guarantee provided by this struct. So we always copy the array to ensure it won't ever change.
return CreateDefensiveCopy(items);
}
编辑:在 GitHub 上有一个关于此功能的请求,这也提供了最快的 hack 使用:https://github.com/dotnet/corefx/issues/28064
【问题讨论】:
-
如果你知道你的元素不会改变,为什么不简单地使用一个普通的数组呢?
-
您为什么要避免复制?这是铸造性能问题吗?您是否过早优化?
-
@sweeper。表现。它用于矢量库,因此必须快速。通过 vector.Add 中的数组进行额外迭代会使性能减半
-
@HimBromBeere。因为我需要为客户端代码授予对数组的只读访问权限
-
返回一个 IReadOnlyList
怎么样?
标签: c# optimization immutable-collections