在运行时动态生成函数以提高性能

Generating function in runtime dynamically to improve performace

我有一个会被超级频繁调用的小函数,基本上它会检查配置值并决定将哪个值设为 return:

string GetKey()
{
    if (Config.UseFirstName)
    {
         return this.firstName;
    }
    else
    {
         return this.lastName;
    }
}

如你所见,很简单,Config.UseFirstName是一个可配置的变量,启动时从本地配置文件中读取,一旦加载,就永远不会改变。鉴于此,我想通过删除 if-else 子句来提高其性能,我想在启动期间确定 Config.UseFirstName 变量时动态生成 GetKey 函数,如果为真,则我将生成这样的函数:

string GetKey()
{
    return this.firstName;
}

希望通过去掉boolean不必要的检查,提高这个函数的性能,其行为类似于Windows平台上的.DLL动态加载。 现在的问题是,.NET 是否支持我的方案?我应该使用 ExpressionTree 吗?

声明一个函数指针

Func<string> GetKey;

在class'构造函数中

MyClass()
{
    if (Config.UseFirstName)
    {
        GetKey = () => this.firstName;
    }
    else
    {
        GetKey = () => this.lastName;
    }
}

调用 GetKey 现在只会 return 正确的属性,而无需评估 Config.UseFirstName。