静态属性/功能的性能

Tim*_*ter 3 .net c# vb.net asp.net performance

在将属性static/shared作为实例属性之前,可能是任何锁定机制时,性能是否存在差异?

HttpCache中有一个使用频繁的对象,可以通过页面实例(Service.aspx)中的属性访问.现在我想知道是否更好地使它静态,因为无论如何HttpCache在应用程序中共享.

我决定使其静态的主要原因是因为它更容易引用(Service.dsRMAvs. ((Service)Page).dsRMA).

我知道静态功能和线程安全可能出现的问题.

感谢您的时间.

之前:

C#

public ERPModel.dsRMA dsRMA {
    get {
        if (Cache("DS_RMA") == null) {
            Cache("DS_RMA") = new ERPModel.dsRMA();
        }
        return (ERPModel.dsRMA)Cache("DS_RMA");
    }
}
Run Code Online (Sandbox Code Playgroud)

VB

Public ReadOnly Property dsRMA() As ERPModel.dsRMA
    Get
        If Cache("DS_RMA") Is Nothing Then
            Cache("DS_RMA") = New ERPModel.dsRMA
        End If
        Return DirectCast(Cache("DS_RMA"), ERPModel.dsRMA)
    End Get
End Property
Run Code Online (Sandbox Code Playgroud)

之后:

C#

public static ERPModel.dsRMA dsRMA {
    get {
        if (HttpContext.Current.Cache("DS_RMA") == null) {
            HttpContext.Current.Cache("DS_RMA") = new ERPModel.dsRMA();
        }
        return (ERPModel.dsRMA)HttpContext.Current.Cache("DS_RMA");
    }
}
Run Code Online (Sandbox Code Playgroud)

VB

Public Shared ReadOnly Property dsRMA() As ERPModel.dsRMA
    Get
        If HttpContext.Current.Cache("DS_RMA") Is Nothing Then
            HttpContext.Current.Cache("DS_RMA") = New ERPModel.dsRMA
        End If
        Return DirectCast(HttpContext.Current.Cache("DS_RMA"), ERPModel.dsRMA)
    End Get
End Property
Run Code Online (Sandbox Code Playgroud)

Luk*_*keH 6

无论如何,你不太可能注意到任何显着的性能差异.(如果有的话,我希望静态版本具有轻微的性能优势.如果微优化真的很重要,可以看看在您的特定情况下会发生什么.)

我建议在应用程序域的上下文中做任何最具语义意义的事情:如果对象在逻辑上属于特定实例,那么使用实例属性; 如果对象在所有实例之间共享,则使用静态属性.