C# Dictionary

Started by
2 comments, last by btower 13 years ago
Hey Everyone,

Im Working on a small2D game engine for myself to use and at the moment im working hardly on the TextureManager class.

My Problem is that I want to check which Sprite belongs to which object and for that I store The Object and Sprite in a Dictionary.
For me this seems to be a cheap and not really performance friendly way to store a whole game object as a key.

/// <summary>
/// Creates a sprite for the refered object
/// </summary>
/// <param name="gameObject">Object</param>
/// <param name="fileName">Texture name</param>
public void CreateSprite(Object gameObject, String fileName)
{
if (this.IsActive)
{
Texture2D tmpTexture;

//Checks if the Texture2D file exists and if the object is already stored
if (this.managerTextureMap.TryGetValue(fileName, out tmpTexture) && !this.managerSpriteObjectMap.ContainsKey(gameObject))
{
this.managerSpriteObjectMap.Add(gameObject, new Sprite(tmpTexture, Vector2.Zero));
}
}
}


Is there any better way to store the right reference between the object and the sprite?
Maybe each object should have a Unique ID made with the HashCode and a random number?

Its just a performance question for me. Maybe not the Object is stored but the Memory adress of the object? I dont know how it works in background ;(

Any Feedback or tips?

Thanks
[size="2"]Java / C# Developer
Advertisement
Make sure you use the generic type Dictionary<TKey, TValue>. This dictionary is implemented as a hashmap, which should perform really well (close to O(N) for lookups).
The non-generic Dictionary is also a hashmap, but you will have to keep casting the key and value. It will be slower.

I wouldn't immediately worry about the performance here, unless profiling tells you otherwise. Using Dictionary<TKey, TValue> is what I would use initially in this case, too.

which should perform really well (close to O(N) for lookups).

Shouldn't that be close to O(1)?
Heh, yes it should! And it is, too! My mistake.

This topic is closed to new replies.

Advertisement