矩阵切片避免拷贝的Span技巧

解读

在国内量化、高频撮合或科学计算面试中,面试官常问“如何在不分配新数组的前提下,对大型 double[,] 做行/列/子块切片”。考点有三:

  1. 是否知道 .NET Core 2.1+ 引入的 System.Span<T> 与 Memory<T>;
  2. 能否用 F# 的 inline、byref-like 语义和 ReadOnlySpan 把二维抽象成一维视图;
  3. 是否意识到 Span 只能驻留栈上,因此必须避开 async/类字段/闭包捕获。
    答“用 Array.Copy”或“yield 序列”会被直接判负,因为都会触发堆分配。

知识点

  • Span<T>、ReadOnlySpan<T> 的栈-only 限制与 GC 无关
  • F# 的 byref-like 属性:[<IsByRefLike>]、byref<'T> in 和 & 取地址
  • 二维数组在 CLR 中是行优先连续块,可用 Unsafe.As 或 MemoryMarshal.Cast 把 double[,] 视为 Span<double>
  • 切片步长(slice stride)与切片长度需显式传递,因为 Span 本身不记录二维形状
  • 高阶函数参数需加 inline + [<InlineIfLambda>] 避免隐式分配
  • 若需跨 await 边界,应把 Span 降级为 Memory<T>,或提前把数据拷进 ArrayPool.Shared 再归还

答案

open System
open System.Runtime.CompilerServices
open System.Runtime.InteropServices

/// 把 double[,] 当成行优先的一维只读视图,零拷贝
let asSpan2D (m: double[,]) : ReadOnlySpan<double> =
    let len = m.Length
    // 拿到第一个元素的托管指针
    let ptr = && m.[0, 0]
    // 从指针构造 Span
    MemoryMarshal.CreateReadOnlySpan(&ptr, len)

/// 行切片:返回第 r 行的 Span,无堆分配
let rowSlice (m: double[,]) (r: int) : ReadOnlySpan<double> =
    let cols = m.GetLength(1)
    let whole = asSpan2D m
    whole.Slice(r * cols, cols)

/// 列切片:返回第 c 列的 Span,步长=列数,仍无拷贝
let colSlice (m: double[,]) (c: int) : ReadOnlySpan<double> =
    let rows = m.GetLength(0)
    let cols = m.GetLength(1)
    let whole = asSpan2D m
    // 手动步长遍历,返回一个自定义的 ColumnSpan 结构体
    ColumnSpan(whole, c, cols, rows)

[<IsByRefLike; NoEquality; NoComparison>]
type ColumnSpan =
    val private whole: ReadOnlySpan<double>
    val private col: int
    val private stride: int
    val private len: int
    new(whole, col, stride, len) =
        { whole = whole; col = col; stride = stride; len = len }

    member this.Item
        with inline get i =
            this.whole.[i * this.stride + this.col]

    member this.Length = this.len

    member this.GetEnumerator() =
        let mutable idx = -1
        { new IEnumerator<double> with
              member _.Current = this.whole.[idx * this.stride + this.col]
          interface System.Collections.IEnumerator with
              member _.Current = box this.whole.[idx * this.stride + this.col]
              member _.MoveNext() = idx <- idx + 1; idx < this.len
              member _.Reset() = idx <- -1
          interface IDisposable with
              member _.Dispose() = () }

使用示例:

let a = array2D [[1.0; 2.0; 3.0]; [4.0; 5.0; 6.0]]
let r1 = rowSlice a 1   // Span [4;5;6]
let c2 = colSlice a 2   // ColumnSpan 可 foreach,无拷贝

整个流程零堆分配,满足高频行情解析或 GPU 上传前的数据准备场景。

拓展思考

  1. 若矩阵存储在 ArrayPool 的共享缓冲区,如何封装成 IDisposable 的 MatrixOwner,保证归还?
  2. 当列切片需要参与 SIMD 计算,如何把 ColumnSpan 连续化到栈上 256-bit 对齐的 buffer,而不触发拷贝?
  3. 在 F# 5+ 的“可恢复状态机”代码中,Span 不能跨越 yield! 点,如何设计“Memory 视图 + 局部 Span”双层 API,既保持异步友好,又保证热路径零分配?