container icon indicating copy to clipboard operation
container copied to clipboard

LifetimeManager optimization

Open ENikS opened this issue 6 years ago • 0 comments

Description

At present LifetimeManager implements several abstract methods to manipulate manager's stored values. These methods are implemented in derived classes and define how managers behave.

Problem

The amount of work involved in getting the value stored in the manager varies with whether it is already stored or still needs to be resolved. For example, ContainerControlledLifetimeManager goes through several steps to get the value:

  • When GetValue is called it enters the Monitor to make sure only one thread is resolving this value.
  • Returns NoValue to indicate that no value has been stored
  • Waits in locked state until container resolves the value and sets it in the manager
  • When value is set via SetValue it releases the lock

Next time the registration is resolved, the manager goes through the same locking routine, although the value is already stored with the container and could be immediately returned:

  • On call to GetValue the manager still enters the monitor
  • Checks if value is already stored
  • Returns the stored value and exits the lock

The locking and unlocking process creates measurable overhead

Solution

The overhead created by unnecessary locking could be avoided if the manager had the way to redirect Get and TryGet to more optimized methods. For that two function pointers are introduced:

public virtual Func<ILifetimeContainer, object> TryGet { get; protected set; }

public virtual Func<ILifetimeContainer, object> Get { get; protected set; }

Normally these just point to TryGetValue and GetValue respectively, but in case of (https://github.com/unitycontainer/abstractions/blob/master/src/Lifetime/Abstracts/LifetimeManager.cs) could be redirected to SynchronizedGetValue, once value has been set.

Impact

Minimal.

ENikS avatar Jun 10 '20 15:06 ENikS