> | | > Dependency Properties -II (Memory Footprint)

Dependency Properties -II (Memory Footprint)

Posted on Thursday, December 19, 2013 | No Comments



This is the second in a series of posts that would discuss various aspects of dependency properties and how they are different. The first aspect is memory footprint of the application in which they are defined.

Scenario:
A user control needs to be created which can be added to any page of the application and allows the user to add the selected item to the shopping cart after specifying the quantity and discount coupon code (optional). This user control would have UI similar to that shown below:

This control should expose a property Quantity, which can be set by the calling page. For example, a page can choose to show the user-control with Quantity pre-populated as 1:

Now suppose the user control’s class exposes this property as a regular CLR property:
public int? Quantity { get; set; }

Suppose this CLR property is exposed and this control is used by 10 products displayed on the screen. Each instance of those 10 instances of this user control would create a property called Quantity. So in the memory of the application, there would be 10 instances of user control - each with its own property Quantity.

If this CLR property is instead converted to a dependency property, there would be a single Quantity property in memory, which would be associated with each instance of the user control class. But how does a single instance of Quantity cater to the different values user may enter for each of those 10 instances? Answer: hashing.

As long as all 10 instances of the user control keep the default value of the property, they all will be sharing the same property in memory. However, if any one of these instances overrides the default value, a separate Quantity property would be spun in memory and would be linked to this particular instance using hashing.


This hashing mechanism is handled by the dependency engine. So as soon as a dependency property is created, a default value Quantity property is spun in memory. The hash is updated for each instance of the control to point to this Quantity. As soon as a control assigns a different value to the Quantity property of the user control, a separate memory location is assigned to that value and it is liked to the corresponding instance of user control using a hash. When that user control's Quantity property is accessed, the hash lookup is performed and the correct value is picked by the dependency engine.

Leave a Reply

Powered by Blogger.