I have a small function which will be called super frequently, basically it checks a config value and decide which value to return:
string GetKey()
{
if (Config.UseFirstName)
{
return this.firstName;
}
else
{
return this.lastName;
}
}
As you can see, it is pretty simple, the Config.UseFirstName
is a configurable variable that read from a local configuration file when starting up, once it is loaded, it will never be changed. Given that, I want to improve its performance by removing the if-else
clause, I want to dynamically generate the GetKey
function when Config.UseFirstName
variable is determined during starting up, if it is true, then i will generate a function like this:
string GetKey()
{
return this.firstName;
}
I hope by eliminating the unnecessary checking of boolean, the performance of this function can be improved, its behavior is similar to .DLL dynamic loading on Windows platform. Now is the question, does .NET support my scenario? Should I use ExpressionTree?
Declare a function pointer
Func<string> GetKey;
In the class' constructor
MyClass()
{
if (Config.UseFirstName)
{
GetKey = () => this.firstName;
}
else
{
GetKey = () => this.lastName;
}
}
Calling GetKey will now just return the correct attribute without having to evaluate Config.UseFirstName.