Can you tell the difference between the following 2 code snippets?
1) Using a Func/Action within a static method
public static class ExpensiveMethodWithAFuncClass<T>
{
public static readonly Func<T> ExpensiveMethod= ExpensiveMethodImplementation();
private static Func<T> ExpensiveMethodImplementaion
{
//some expensive operations here
// returns a compiled delegate
}
}
2) Same class without using a Func<T>
public static class ExpensiveMethodClass<T>
{
public static T ExpensiveMethod
{
//build the expression here, compile and invoke the expression
}
}
Answer : In 1) when we call ExpensiveMethod, the implementation ExpensiveMethodImplementation() is executed only once.
In the case of 2) we will execute ExpensiveMethod every time we call it.
If the implementation is an expensive operation, 1) will benefit from using the delegate Func<T>
No comments:
Post a Comment