Search code examples
c#resourcesdrawxna-4.0monogame

Draw script eating up memory and cpu


I've been using this script to draw lines, and it works, but when I run my game it starts eating up my resources like no one's business.

public static void DrawLine(Vector2 start, Vector2 end, Color color, int width, float alpha, float depth)
{
                                // GraphicsDevice stored in other class
    var texture = new Texture2D(Graphics2D.GraphicsDevice, 1, 1);
    texture.SetData(new[] { color });

    Vector2 edge = end - start;
    float angle = (float)Math.Atan2(edge.Y, edge.X);

    // SpriteBatch stored in other class
    Graphics2D.SpriteBatch.Draw(
        texture,
        new Rectangle(
        (int)start.X,
        (int)start.Y,
        (int)edge.Length(),
        width),
    null,
    Color.White,
    angle,
    new Vector2(0, 0),
    SpriteEffects.None,
    1.0f);
}

Memory and CPU usage begin to spike as soon as lines start being drawn.

Memory usage spikes as soon as lines start being drawn.

Any guesses as to why it's doing this? Should I even be overly concerned? Or is this normal for these kinds of operations.


Solution

  • As @Norris mentions in the comment, create the texture at Initialize, and reuse it.

    The reason it's eating up your CPU is because you're creating an entirely new texture from scratch EVERY FRAME. This is heavy, because you're asking the GPU to reserve memory and power for creating a new texture, using it that single frame, disposing it again, and the next frame you repeat the process. There is a reason Photoshop has progress bars when doing some changes to large-ish images.

    Even if it wasn't cpu-intensive, it is bad practise to recreate something every frame, if you don't have to. Always reuse as much as possible. This goes for all types of applications, but is especially important in game development due to the 60fps draw loop. About the only objects this does not apply to, are basic value-types such as Ints, Floats, Vector3's, Matricies, etc. Unless of course these values are based on calculations that needs to occur every frame.

    To summarise: Always perform as little work as possible to accomplish your intended goal