jeudi 5 février 2015

Delegate vs if statement

I have a class:



public class MyClass: IMyInterface
{

int _parameter;
public Myclass(int parameter)
{
_parameter = parameter;
//Do other things
}

public int FrequentlyCalledFunction()
{
if(_parameter == 0)
{
return 0;
}
else
{
int result;
//Do some calculations
return result;
}
}

}


Since the _parameter is assigned once in the constructor, entering the if statement every time the FrequentlyCalledFunction is called seems somewhat inefficient for an already created instance . Thus, I thought to modify the code as follows. Declare a delegate



public delegate int MyDlg();


public class MyClass: IMyInterface
{

int _parameter;
MyDlg _intermediate;
public Myclass(int parameter)
{
_parameter = parameter;
_intermediate = _parameter == 0 ? _returnZero : _calculateAndReturn;

//Do other things
}


public int FrequentlyCalledFunction()
{
return _intermediate();
}

int _returnZero()
{
return 0;
}
int _calculateAndReturn()
{
int result;
//Do some calculations
return result;
}

}


So now, the check will be performed only once at the moment of creating the instance. On the other hand the if statement is replaced with an additional delegate call.


The question is, assuming that the performance is very important, which approach is better?


P.S. The FrequentlyCalledFunction is a method from the interface IMyInterface, thus, I cannot define a MyDlg FrequentlyCalledFunction and call it from the outside of the class.


Aucun commentaire:

Enregistrer un commentaire