Question

I'm having trouble deciding which way to implement my code for drawing a collision rectangle. What is the best practice for doing this. Is it ok to instantiate a new rectangle on every drawcall, with the correct size and location like this:

public void Draw(SpriteBatch spriteBatch)
        {
            Rectangle topLine = new Rectangle(CollisionRect.X, CollisionRect.Y, CollisionRect.Width, 1);
        }

Or is it better to create the rectangle in my fields, and then just change the values of the already existing object in my draw method like this, even though the code is gonna be more "messy"

public void Draw(SpriteBatch spriteBatch)
{
    topline.Height = 1;
    topline.Width = CollisionRect.Width;
    topline.X = CollisionRect.X;
    topline.Y = CollisionRect.Y;

}
Was it helpful?

Solution

I would go with first option. If topLine is no longer needed after the scope of the Draw method it should ideally go as a "local variable".

You need to have a field only when you need it after the scope of Draw method.

OTHER TIPS

I would do second, so less job for GC. But if you have time, draw several 1000 with first and then second. Check if the performance you won worth for the trouble of messiness :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top