簡體   English   中英

C# 這是 ReadOnlySpan 的正確用法嗎<t> ?</t>

[英]C# is this a correct usage of ReadOnlySpan<T>?

動機:我正在開發一款軟件,它應該盡可能地從它運行的機器上榨取盡可能多的性能。

假設: .NET 6 中的任何array都可以在幕后轉換為ReadOnlySpan<T>或其變體。

問題:如果將array中的所有function 傳遞參數替換為ReadOnlySpan<T>是否有任何性能優勢?

具體例子:

private float MethodWithArrayOfFloats(float[] arr)
{
    float sum = 0;
    for (var index = 0; index < arr.Length; index++)
    {
        sum += arr[index];
    }
    //What if I would have called here another method passing this array parrameter ?
    return sum;
}

private float MethodWithArrayOfSpans(ReadOnlySpan<float> arr)
{
    float sum = 0;
    for (var index = 0; index < arr.Length; index++)
    {
        sum += arr[index];
    }
    //What if I would have called here another method passing this ReadOnlySpan parrameter ?
    return sum;
}

其他觀察:

  • 在問這個問題之前,我已經使用DotNetBenchmark分析了這兩種方法,並發現ReadOnlySpan<T>方法在5_000_000次迭代中實際上快了大約 1毫秒
  • Sharplab.io上的 JIT ASM 代碼生成表明,第二種方法產生的指令比第一種方法多(甚至包含一些額外的jmp指令)

N. 盡管如此,這對我來說還是個謎。 將此技術應用於所有場景是否是一種好的做法? 如果不是,為什么它看起來更高效? 隱藏的含義是什么?

從我的角度來看,使用ReadOnlySpan<T>應該總是更高效。 由於ReadOnlySpan<T>是一個引用結構,因此存在一些限制。 因此代碼的可維護性降低。 因此,如果您所做的是在關鍵解決方案的熱路徑上,請使用 ReadonlySpan,如果它適合並且不會使您的代碼復雜化,則不使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM