Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of static properties/functions

is there a difference in performance when making properties static/shared that were instance properties before, maybe any locking mechanisms?

There is a heavily used object in HttpCache which was accessible through a property in a page-instance(Service.aspx). Now i wonder if it would be better to make it static because the HttpCache is shared across the application anyway.

The main reason i decided to make it static was because it is simpler to reference(Service.dsRMA vs. ((Service)Page).dsRMA).

I'm aware of the problems that can occur regarding static functions and thread safety.

Thank you for your time.

Before:

C#

public ERPModel.dsRMA dsRMA {
    get {
        if (Cache("DS_RMA") == null) {
            Cache("DS_RMA") = new ERPModel.dsRMA();
        }
        return (ERPModel.dsRMA)Cache("DS_RMA");
    }
}

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

After:

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");
    }
}

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
like image 338
Tim Schmelter Avatar asked Dec 13 '22 14:12

Tim Schmelter


2 Answers

You're unlikely to notice any significant performance difference either way. (If anything, I would expect the static version to have a slight performance benefit. Benchmark to see what happens in your particular situation if the micro-optimisation is genuinely important.)

I would recommend doing whatever makes the most semantic sense in the context of your application domain: If the object logically belongs to a particular instance then use an instance property; if the object is shared between all instances then use a static property.

like image 83
LukeH Avatar answered Dec 30 '22 02:12

LukeH


If there isn't any threading or management issue, static methods are faster (not very faster), in fact instance methods are static methods with implicit this parameter.

Edit: by saying static methods and instance methods different is this, I didn't mean the way of calling, first one is managed in heap and second one in stack.

like image 21
Saeed Amiri Avatar answered Dec 30 '22 01:12

Saeed Amiri