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