Dictionary Boxing

1k Views Asked by At

I'm using the Microsoft XNA Game Studio 4.0 as a template for my project.

In this project I have a base class for all entities, projectiles, et cetera, called Sprite.

I am planning to use a singleton to handle all of the Sprites so I don't have to create a new Sprite every time I need it if it has been used before.

This is preferred since Sprites have a Texture2D field among other fields that could eat up memory, given enough Sprites are created.

Here is part of my Texture2D singleton as a reference:

public static class TextureManager{
    private static Dictionary<string, Texture2D> allTextures = new Dictionary<string, Texture2D>();
    public static Texture2D GetTexture(string name){
        if(allTextures.ContainsKey(name))
            return allTextures[name];

        ... //Code to handle and create a new key is omitted for simplicity's sake

        return newTexture; //The new texture created from the "name" key
    }
}

This singleton is preferred over just creating the new Texture2D from the content pipeline every time it is needed. The code was derived from this answer.

When planning the Sprite singleton, it occurred to me that boxing would have to occur for the singleton to work on one Dictionary, since essentially all of my entity and projectile classes would inherit the Sprite class.

QUESTION:

Is boxing/unboxing on one Dictionary more efficient than having multiple Dictionarys for each type of Sprite?

1

There are 1 best solutions below

2
TheGeneral On BEST ANSWER

This is not boxing...

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.

Boxing happens when a value of value type is converted to a reference type. Casting a reference type to its base type is not boxing/unboxing.

Casting isn't very expensive, though it will incur a cost, as will a switch statement, or a typeOf or any other method.

In short, you will have to perform benchmarks to really get to the bottom of your problem for micro-optimization. However, i think storing as base type would be fine in my opinion.


Additional resources