How to Optimize Usage of Hundreds of Thousands of Qt QRect Class

If you’re planning on using hundreds of thousands of rectangles in your Qt application, you might be surprised that it might not perform at optimal speeds. Here’s how I speed up my Qt applications…

By Chongchen Saelee

If you’re not already aware, I’m building my own 2D game engine, SDXM, which will require hundreds of thousands of rectangle structures to be processed prior to drawing their abstracted form to the screen. In my experience, I’ve found using Qt’s convenience class QRect to slow down later on in the game running process when the object count increases exponentially. This is possibly due to QRect having a bunch of convenience methods and functions, which creates an overhead per instantiated object. Imagine, it’s like going to war with a vest full of grenades, handguns, stabbing weapons, bazookas, etc., when all you’re mission is to dig a fox hole.

So what I do is I create my own rectangle structure. (The really hip 3D programmers stopped calling a 4-variable structure rectangle a long time ago and are calling it quad now; I’m not working with 3D, so rectangle makes more sense to me)

  struct Rect{
    int x, y;
    int width, height;

  Rect rectangle;

So now you have your rectangle, which you can create tons of with a QList or QVector, and you can use the [] operator to access them individually. You’ll notice that there is great improvement in your processing, especially if you’re working with hundreds and thousands of objects.

However, you’ll have to calculate everything else by yourself, which still isn’t that big a deal because you’d only be implementing exactly the methods and functions that you’ll need.

And note, a structure is smaller and faster than a class because it doesn’t have any functions or methods.

I hope this helps my fellow Qt users out there!

Tags: , , , , , , , , , , , , , , ,

Comments are closed.