2017-04-21 58 views
-2

出於性能原因,我試圖減少每次調用特定方法時創建的引用類型的新實例的開銷。C#靜態內聯方法參數

作爲一個基本的例子:

public int AccumulativeCount(Expression<Func<int>> exp) 
{ 
    // usually do something useful with "exp". Instead put a 
    // breakpoint and get the memory reference of exp via "&exp" 
    return 1; 
} 

當在代碼中的其他地方稱爲,EXP在AccumulativeCount方法的參考不同的是:

AccumulativeCount(() => 7); 

有一種方法使來自調用代碼的參數static inline?在上面的例子中,參數「()=> 7」顯然永遠不會改變,所以每次都不應該重新創建它。

我知道,我可以改變調用代碼爲:

public static Expression<Func<int>> MyStaticCountExp =() => 7; 
// ... later in the code 
AccumulativeCount(MyStaticCountExp); 

之所以我反對上面是表達纔有意義,因爲它是一個參數的上下文。此外,代碼並不像它那樣乾淨。有什麼樣:

AccumulativeCount(static() => 7); // does not compile 
+1

我非常懷疑你會注意到任何可感知的性能影響。如果您打算進行微小的優化,您應該準備好以靜態字段的形式存在更多不可讀的代碼。 – Rob

+2

花費寶貴的時間解決實際存在問題的問題。 –

回答

0

我不知道到底你的用例,但也許Lazy<T>類會有所幫助。

public static readonly Lazy<int> Something = new Lazy<int>(() => AccumulativeCount(() => 7)); 
    public static int AccumulativeCount(Expression<Func<int>> exp) { 
     // usually do something useful with "exp". Instead put a 
     // breakpoint and get the memory reference of exp via "&exp" 
     return 1; 
    } 
    public static void DoSomething() { 
     // the value was not available, so the AccumulativeCount(...) will be called 
     var a = Something.Value; 

     // the value is already created, no more call of AccumulativeCount(...) is needed 
     var b = Something.Value; 
     var c = Something.Value; 
     var d = Something.Value; 
    }