jeudi 24 novembre 2022

Should I preallocate a vector

From an efficiency standpoint, would it be better to

  1. allocate enough memory for a vector<unique<Base*>> and downcast one by one or
  2. use polymorphism and insert(new Derived()) in combination with virtual functions (easy and straightforward). Should I even consider the first approach? Wouldn't I have to reset every unique_ptr? Also, would factory pattern be a better solution in my case?
class Chunk
{

public:
    uint32_t ChunkType;
;
class OldPaletteChunk : public Chunk;
class ColorProfileChunk: public Chunk;

So far I was preallocating the vector<unique<Chunk>> knowing the number of elements I needed to store. During runtime I would parse the file and read chunks of data based on their type:

switch (chunk->m_ChunkType) // Chunk::ChunkType
{
    case 0x0004:    // 0-255
    case 0x0011:    // 0-63
        readOldPaletteChunk(chunk); // dynamic_cast here?
    case 0x2007:    
        readColorProfileChunk(dynamic_cast<ColorProfileChunk*>(chunk)); // doesn't work
...
}

Aucun commentaire:

Enregistrer un commentaire