You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# record struct传递方式、blittable特性及性能优化咨询

关于C# record struct的拷贝行为、blittability及对象池复用的疑问

问题背景

在处理大量struct及其数组、列表时,我一直受困于如何减少传递或操作过程中struct拷贝的问题。由于必须使用blittable类型,只能采用struct实现。我试过ErrorProne.NET这类辅助工具,但对当前的解决方案仍不满意。

核心疑问

在最新版C#和.NET中,record类型可用于struct、类或独立定义,但我找不到关于record struct的以下明确信息:

  • 传递拷贝行为与普通struct的差异
  • 是否可作为blittable类型使用
    另外,我希望结合自定义ObjectPool来复用这些结构体,避免重复分配内存及GC回收带来的开销,但不确定这种方案的可行性。

代码示例

[StructLayout(LayoutKind.Sequential)]
public record struct PagedSecondaryIndexKey
{
    [MarshalAs(UnmanagedType.U1)]
    public SecondaryIndexType IndexType;

    [MarshalAs(UnmanagedType.U8)]
    public ulong Page;
    
    [MarshalAs(UnmanagedType.Struct)]
    public IndexIdentifier IndexIdentifier;
    
    public PagedSecondaryIndexKey(ulong page, SecondaryIndexType indexType, ulong identifier1, ulong identifier2, ulong identifier3)
    {
        IndexType = indexType;
        Page = page;
        IndexIdentifier.Reset(identifier1, identifier2, identifier3);
    }

}

[StructLayout(LayoutKind.Sequential)]
public record struct IndexIdentifier
{
    [MarshalAs(UnmanagedType.U8)]
    private ulong IndexIdentifier1;

    [MarshalAs(UnmanagedType.U8)]
    private ulong IndexIdentifier2;
    
    [MarshalAs(UnmanagedType.U8)]
    private ulong IndexIdentifier3;
    
    public const int Size = 3 * sizeof(ulong);
    
    public IndexIdentifier(ulong identifier1, ulong identifier2, ulong identifier3)
    {
        IndexIdentifier1 = identifier1;
        IndexIdentifier2 = identifier2;
        IndexIdentifier3 = identifier3;
    }
    
    public IndexIdentifier(IndexIdentifier indexKeyIndexIdentifier)
    {
        indexKeyIndexIdentifier.IndexIdentifier1 = IndexIdentifier1;
        indexKeyIndexIdentifier.IndexIdentifier2 = IndexIdentifier2;
        indexKeyIndexIdentifier.IndexIdentifier3 = IndexIdentifier3;
    }

}

内容的提问来源于stack exchange,提问作者cmadh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 10:01:43