0

为了说明的目的,我编了两个函数。你能建议我哪一个更好的练习吗?

Test2 是否对性能更好,因为它需要声明更少的变量,因此可以在系统上使用更少的内存?

Function Test1()

    Dim PerformMethod_A As Boolean = True
    Dim a = 1
    Dim b = 2
    Dim c = 3
    Dim d = 4
    Dim e = 5
    Dim result

    If PerformMethod_A Then
        result = a + b
    Else
        result = c + d + e
    End If

    Return result

End Function

Function Test2()

    Dim PerformMethod_A As Boolean = True
    Dim result

    If PerformMethod_A Then
        Dim a = 1
        Dim b = 2
        result = a + b
    Else
        Dim c = 3
        Dim d = 4
        Dim e = 5
        result = c + d + e
    End If

    Return result

End Function
4

2 回答 2

2

此时,您正在执行微观性能增强。对于您描述的问题陈述,无论哪种方式都不会有明显的区别。如果您在性能方面遇到问题,您需要首先收集指标,这样您就知道要调整什么。

阅读Eric Lippert 的这些文章,它们将为您提供指导。

于 2013-08-06T10:24:33.893 回答
1

如果你看看它在 IL 中编译成什么,你会发现它并没有真正的不同。所有局部变量实际上都在 IL 方法的顶部声明,无论它们在源代码中的什么位置声明。

测试1:

    // Method begins at RVA 0x2054
// Code size 59 (0x3b)
.maxstack 2
.locals init (
    [0] int32 a,
    [1] int32 b,
    [2] int32 c,
    [3] int32 d,
    [4] int32 e,
    [5] bool PerformMethod_A,
    [6] object result,
    [7] object Test1,
    [8] bool VB$CG$t_bool$S0
)

测试2:

// Method begins at RVA 0x209c
// Code size 58 (0x3a)
.maxstack 2
.locals init (
    [0] bool PerformMethod_A,
    [1] object result,
    [2] object Test2,
    [3] int32 a,
    [4] int32 b,
    [5] int32 c,
    [6] int32 d,
    [7] int32 e,
    [8] bool VB$CG$t_bool$S0
)
于 2013-08-06T12:28:11.273 回答