Search code examples
c#.netoptimization

C# Property Access Optimization


In C# (or VB .NET), does the compiler make attempts to optimize property accesses? For eg.,


public ViewClass View
{
    get
    {
        ...
        Something is computed here
        ....
    }
}

if (View != null)
    View.Something = SomethingElse;


I would imagine that if the compiler could somehow detect that View remains constant between the two accesses, it can refrain from computing the value twice. Are these kind of optimizations performed?

I understand that if View has some intensive computations, it should probably be refactored into a function (GetView()). In my particular case, View involves climbing the visual tree looking for an element of a particular type.

Related: Any references on the workings of the (Microsoft) C# compiler?


Solution

  • Not in general, no. As Steven mentioned there are numerous factors to consider regarding multithreading, if you truly are computing something that might change, you're correct it should be refactored away from a property. If it won't change, you should lazy-load it (check if the private member is null, if so then calculate, then return the value).

    If it won't change and depends on a parameter, you can use a Dictionary or Hashtable as a cache - given the parameter (key) you will store the value. You could have each entry as a WeakReference to the value too, so when the value isn't referenced anywhere and garbage collection happens, the memory will be freed.

    Hope that helps.