I am currently working on a OpenGL Renderer in C++. I have created a base Object class that looks a bit like this:

class Object
    std::vector<Vertex> vertices;
    std::vector<uint16_t> indices;

Vertex is a simple struct containing the data of a vertex.

struct Vertex
    glm::vec3 location;
    glm::vec4 color;

Anything being rendered is considered an Object. The vertex data of each Object needs to change every frame, so my vertex buffer allocates a certain amount of memory on startup and the vertex data of all Objects is uploaded to the GPU each frame using glBufferSubData. I then have a Scene class which stores a vector of all the existing Objects. The Renderer merges the vertex data of each object every frame like this:

std::vector<Vertex> all_vertices;
std::vector<uint16_t> all_indices;

for (const Object* object : objects)
    all_vertices.insert(all_vertices.end(), std::make_move_iterator(object->get_vertices_begin()), std::make_move_iterator(object->get_vertices_end()));
    all_indices.insert(all_indices.end(), std::make_move_iterator(object->get_indices_begin()), std::make_move_iterator(object->get_indices_end()));

draw(vertices, indices);

My concern here is the performance of these operations, especially all the heap allocations by std::vector. The Renderer can't know how many total vertices and indices there are, since this could change any frame


1 Answer 1


You could use std::vector::reserve to reserve the same amount of space that you have determined the GPU will need. Then use std::vector::clear in each frame before you start pushing things in.

This way you only allocate from the heap once, as long as you don't push more than you reserved.

It's worth noting that you can override the std allocator and provide your own one if you want to take control of std container allocations. But that's another topic for another question. As is whether you should even use std containers.

Top tip: measure performance before and after making optimisation changes to check that your assumptions are correct.


You must log in to answer this question.

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