Skip to main content

Optimization through WeakReference

WeakReference is a new element added into 4.5 framework, but it was available in Java from the earlier stage only. So, this article could be useful for .Net, Java, and Android as well.

What is it?
It is nothing more than a class but what special about is to interact with Garbage Collector in a certain way which could help out in optimization.

Scenario
We all know that static members are created and shared throughout the application and life cycle by maintaining only single instance. Possibly it can useful in cases where data need to be frequently accessed but what about those that doesn't need to be frequently accessed all times. Those data might be resource hungry data so static or some kind of caching mechanism is required. Storing something in static members or caching increases memory footprint for the application. This is once situation, but there might be other situation as well.
WeekReference is a technique to hook up member with Garbage collector to retrieve actual object if it is not garbage collected. That means we can get the object if it is not garbage collected and re-create new one if it is not there in memory. This will allow object to be garbage collected and at same time create new item if does not exists which would be great under high traffic with frequent data access by keeping memory footprint under control in high and low traffic.

Coding
Theoretically it  looks complex but it is much easier on the implementation side. Just creation of values and setting under the WeekReference.
I have repeated some code to make it look simple at first glance.

   private static WeakReference<List<string>> WeekRefObj;  
   public static List<string> GetObject()  
   {  
     List<string> values;  
     if (WeekRefObj == null)  
     {  
       // TODO: Create new resource hungry object.  
       values = new List<string>();  
       WeekRefObj = new WeakReference<List<string>>(values);  
       return values;  
     }  
     if (WeekRefObj.TryGetTarget(out values))  
     {  
       return values;  
     }  
     else  
     {  
       // TODO: Create new resource hungry object.  
       values = new List<string>();  
       WeekRefObj.SetTarget(values);  
       return values;  
     }  
   }  

WeakReference has one parameter constructor which takes the actual values.
 WeekRefObj = new WeakReference<List<string>>(values);       

TryGetTarget is a function to get the value if it is not garbage collected and the SetTarget is for setting the new value.

These are the only three things that we need to know for coding.

Going to next stage
Since the implementation is much simple but codes increase a little. This is an extension wrapper method to make it more simple.

  /// <summary>  
   /// Gets or add the <see cref="WeakReference"/> object.  
   /// </summary>  
   /// <typeparam name="T">The type of the object need to save or get.</typeparam>  
   /// <param name="weekReference">The week reference object.</param>  
   /// <param name="getItemCallback">The get item callback for <see cref="WeakReference"/> value.</param>  
   /// <returns><see cref="WeakReference"/> value.</returns>  
   public static T GetOrAdd<T>(this WeakReference<T> weekReference, Func<T> getItemCallback)  
     where T : class  
   {  
     if (weekReference == null)  
     {  
       weekReference = new WeakReference<T>(default(T));  
     }  
     T value;  
     if (weekReference.TryGetTarget(out value))  
     {  
       return value;  
     }  
     else  
     {  
       if (getItemCallback == null)  
       {  
         throw new ArgumentNullException("getItemCallback");  
       }  
       value = getItemCallback();  
       weekReference.SetTarget(value);  
       return value;  
     }  
   }  

Usage

      private static WeakReference<List<string>> ModelPropertyMapping = null;  
      var modelMapping = ModelPropertyMapping.GetOrAdd(() =>  
      {  
           // TODO: Create new resource hungry object.  
           var mapping = new List<string>();  
           return mapping;  
      });  

The extension method would take care of object creation based on need.

SOURCE: http://www.mindfiresolutions.com/Code-optimization-through-WeekReference-2693.php

Popular posts from this blog

Architecture solution composting Repository Pattern, Unit Of Work, Dependency Injection, Factory Pattern and others

Project architecture is like garden, we plant the things in certain order and eventually they grow in similar manner. If things are planted well then they will all look(work) great and easier to manage. If they grow as cumbersome it would difficult to maintain and with time more problems would be happening in maintenance.

There is no any fixed or known approach to decide project architecture and specially with Agile Methodology. In Agile Methodology, we cannot predict how our end products will look like similarly we cannot say a certain architecture will fit well for entire development lifespan for project. So, the best thing is to modify the architecture as per our application growth. I understand that it sounds good but will be far more problematic with actual development. If it is left as it is then more problems will arise with time. Just think about moving plant vs a full grown tree.

Coming to technical side, In this article, I will be explaining about the various techniques tha…

LDAP with ASPNet Core Identity in MVC Core

Lightweight Directory Access Protocol (LDAP), the name itself explain it. An application protocol used over an IP network to access the distributed directory information service.

AspNet Identity Core is a new offering from Microsoft in replacement of AspNet Identity for managing users.

In this tutorial, we would be looking for implementing LDAP with AspNet Identity Core to allow users to be able to log in through AD or AspNet Identity Core members.

The first and foremost thing is to add references for consuming LDAP. This has to be done by adding reference from Global Assembly Cache (GAC) into project.json

"frameworks": { "net461": { "frameworkAssemblies": { "System.DirectoryServices": "4.0.0.0", "System.DirectoryServices.AccountManagement": "4.0.0.0" } } },
These System.DirectoryServices and System.DirectoryServices.AccountManagement references are used to consume LDAP functiona…

Configuring Ninject, Asp.Net Identity UserManager, DataProtectorTokenProvider with Owin

It can be bit tricky to configure both Ninject and Asp.Net Identity UserManager if some value is expected from DI to configure UserManager. We will look into configuring both and also use OwinContext to get UserManager.

As usual, all configuration need to be done on Startup.cs. It is just a convention but can be used with different name, the important thing is to decorate class with following attribute to make it Owin start-up:

[assembly: OwinStartup(typeof(MyProject.Web.Startup))]
Ninject configuration

Configuring Ninject kernel through method which would be used to register under Owin.

Startup.cs
public IKernel CreateKernel() { var kernel = new StandardKernel(); try { //kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); // TODO: Put any other injection which are required. return kernel; } catch { kernel.Dispose(); throw; }…