c# - 将不同的数字类型作为参数发送到方法时是否存在性能问题?

标签 c# .net windows jit

鉴于此功能:

void function(Double X, Double y, Double Z);

如果我发送不同的数字数据类型,是否会出现性能问题?例如:

function(1, 2, 3); //int, int, int
function(1, 2.2, 1); //int, double, int
function(1.3f, 3.4, 2.34f) //single, double, single
function(1.2f, 1, 1) //single, int, int

.NET JIT 如何管理它?它进行装箱-拆箱?这会影响性能吗?

最佳答案

您的确切示例将由编译器转换,因此没有性能损失。如果我们稍微修改一下示例:

static void Test(double x, double y, double z)
{
    Console.WriteLine(x * y * z);
}

static void Main()
{
    double d1 = 1;
    double d2 = 2;
    double d3 = 3;
    float f1 = 1;
    float f2 = 2;
    float f3 = 3;
    int i1 = 1;
    int i2 = 2;
    int i3 = 3;

    Test(i1, i2, i3);
    Test(i1, d2, i3);
    Test(f1, d2, f3);
    Test(f1, i2, i3);
}

那么故事就不一样了。编译器不太可能为我们做转换,所以它有必要为转换发出代码,例如,让我们看一下第二次调用 Test 的代码。

IL_004b:  ldloc.s    V_6    // Load the variable i1 onto the stack
IL_004d:  conv.r8           // Convert it to a double
IL_004e:  ldloc.1           // Load the variable d2 onto the stack
IL_004f:  ldloc.s    V_8    // Load the variable i3 onto the stack
IL_0051:  conv.r8           // Convert it to a double
// And call the function:
IL_0052:  call       void Example.ExampleClass::Test(float64,
                                                   float64,
                                                   float64)

您可以看到它必须为两个非 double 分别发出一条指令。这不是一个免费的 Action ,需要时间来计算。

综上所述,我很难想象这很重要,除非您在非常紧密的循环中调用此函数。

编辑

另外,请留意属性访问器。例如,如果演示对象在 for 期间不改变它的长度,这两种方法在逻辑上是相同的。循环,但第一个会调用 demo.Length多次,这肯定比调用一次慢。

var demo = CreateDemo();
for (int i = 0; i < demo.Length; ++i)
{
    // ...
}

// .. vs ..

var demo = CreateDemo();
int len = demo.Length;
for (int i = 0; i < len; ++i)
{
    // ...
}

关于c# - 将不同的数字类型作为参数发送到方法时是否存在性能问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38406491/

相关文章:

c# - 如何监控真正的页面点击

c# - asp mvc 核心 url 本地化

.net - WPF GUI 负责什么?

c++ - 在 C++ 中访问 UNC 驱动器/远程网络驱动器

windows - 在 Windows 下故意使外部进程崩溃

c# - 将 datetime 转换为 json 格式时出现 WCF 错误

C# 检测用户现在是否使用计算机

.net - 与 Lucene .Net 相比,使用 solr 有什么优势?

c# - 异常处理

C#检测所有窗口中的按键事件