2017-04-21 11 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; 
} 

、AccumulativeCount方法のEXPの参照が異なります。

AccumulativeCount(() => 7); 

にする方法はあります呼び出しコード静的インラインからのパラメータ?上記の例では、パラメータ "()=> 7"は決して変更されないので、毎回再作成する必要がある理由はありません。

は私があることを呼び出すコードを変更することができることを承知している:

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

私は上記反対だ理由は、式が唯一それがためのパラメータであるコンテキストで理にかなっています。また、コードはできるだけクリーンではありません。私は正確にあなたのユースケースを知らないが、多分Lazy<T>クラスが役立ちます

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

私は、このことからパフォーマンスに目に見える影響があることに気づくことは間違いありません。そのような微小な最適化を行う場合は、静的フィールドの形でコードを読むことができるようにする必要があります。 – Rob

+2

実際に問題となっている問題を解決するために貴重な時間を費やしてください。 –

答えて

0

:のようなものがあります。

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; 
    }