This is a very simple question.

Let's say my render loop runs at 60Hz, in each call to render(), I draw all my game's buildings, characters and scenery to make the current frame ready. Each of these entities are drawn using its own instance of a RectangleShape, which is a class able to render a texture to the screen. (I am using OpenGL but it shouldn't be relevant)

RectangleShape is a class that once allocated, generates geometry for the "sprite" to be drawn, has some properties to configure and then renders itself using OpenGL.

The problem is, for each entity, I am allocating the RectangleShape object, configuring and rendering it inside render(). So, in practice, there are dozens if not hundreds of blocks like this inside render():

// pseudocode
RectangleShape entitySprite;

I am aware I have a performance decrease by not using a pre allocated RectangleShape, already configured, which I only call render() on. I know that is the optimal path to go, but my question is:

Will so many allocations/deallocations of RectangleShape (hundreds, 60 times a second) fragment memory over time, decreasing the performance of the whole program? Or can I be safe that despite the performance hit by on-demand allocation is constant and will not degenerate as time passes?

I am not using any kind of custom allocator for anything. Also, please have in mind that the RectangleShape constructor internally resizes a std::vector, which I think implies a heap allocation.



1 Answer 1


Assuming that you're in C++ (which is what your code looks like), creating local instances of RectangleShape inside a function will not cause memory fragmentation. Those variables are being created on the stack, and so their memory will cleanly go away when the stack frame is cleaned up when the function returns.

Do note, though, that if the RectangleShape itself allocates memory on the heap using new or malloc() (or certain other malloc()-like calls), then those allocations could conceivably lead to memory fragmentation, depending on what other heap allocations are occurring and how long-lived those other allocations might be.

  • \$\begingroup\$ Thank you. If this information is correct, it is the answer I was looking for :) \$\endgroup\$
    – Grimshaw
    Dec 14, 2013 at 16:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .