【发布时间】:2018-02-18 15:52:47
【问题描述】:
我有一个函数,它获取一个指向大小为 4 的数组的指针(总是),并且必须只对唯一元素进行切片并返回它们。这个函数每秒被调用 100k 次,这就是为什么它需要快速并且不会对 GC 造成太大压力(这就是为什么缓冲区变量是指针 - stackalloc)。
private const int BufferLength = 4;
private static unsafe ReadOnlySpan<int> SliceUnique(int* buffer)
{
// TODO: move the unique elements to the front
// and get the last unique index
return new ReadOnlySpan<int>(buffer, lastUniqueIndex + 1);
}
// Example:
// input: [1, 3, 2, 1] | [1, 4, 4, 4]
// output: [1, 3, 2] (order doesn't matter) | [1, 4]
【问题讨论】:
-
您能否提供一个或两个应该产生的输入和结果示例。 (特别是定义什么不是唯一元素)。
-
@Richard input: [1, 3, 3, 4] -> [1, 4, 3] 或 [1, 3, 4] (顺序无关紧要),输入 [2323, 4321, 11, 11] -> [2323, 4321, 11]
-
总是四个元素?只是一堆
ifs 怎么样?不会有那么多不同的输入... -
@Haukinger 是的,总是 4。也许 ifs 带有某种 Sorting Network,针对长度为 4 的数组进行了优化
标签: c# arrays performance pointers unsafe