Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding boxing/unboxing in Dictionary with object TValue

Sometimes we need to store a collection of key value pairs in dictionary with various value types. Suppose we want to store a form which consist with boolean, int, string values. Some of these values are kind of ValueType and when we cast them to a ReferenceType such as object it causes boxing.

According to these references:

  • .NET Performance Tips
  • How To Avoid Boxing And Unboxing In C#

Boxing and Unboxing impact our our performance such as GC pressure. The question is is there any way to avoiding boxing/unboxing in Dictionary which its TValue is object.

Dictionary<string, object>

How to avoiding boxing and unboxing in this scenario?

like image 804
Soheil Alizadeh Avatar asked Oct 17 '25 05:10

Soheil Alizadeh


1 Answers

You can avoid storing multiple boxed instances of the same values by implementing a cache of pre-boxed values that are used frequently. For example if the number 0 and the boolean false are inserted frequently as values, you could implement a memory-optimized dictionary like this:

public sealed class ObjectDictionary<TKey> : Dictionary<TKey, object>
{
    private readonly object _cached_0 = 0;
    private readonly object _cached_false = false;

    public new void Add(TKey key, object value)
    {
        if (value is int && (int)value == 0)
        {
            base.Add(key, _cached_0);
        }
        else if (value is bool && (bool)value == false)
        {
            base.Add(key, _cached_false);
        }
        else
        {
            base.Add(key, value);
        }
    }
}

The original boxed zeros and falses that are passed to the Add method will then be eligible for garbage collection immediately, since they won't be stored inside the dictionary. If this is still a problem for the garbage collector, then the origin of the problem is not the dictionary but something else.

Note that inheriting from Dictionary<TKey, object> is probably not a very good idea. The code sample above is just for demonstration of the concept.

like image 195
Theodor Zoulias Avatar answered Oct 19 '25 20:10

Theodor Zoulias



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!