samedi 3 juillet 2021

Optimizing C++ code with std::vector and shared_ptr

Our teacher is teaching us some optimization technics and for that she has given following code in c++ to us for optimization.

struct IStruct
{
    virtual bool GetType() const = 0;
};

struct FStructA : public IStruct
{
    std::string Key;
    int IntData;

    virtual bool GetType() const override
    {
        return true;
    }
};

struct FStructB : public IStruct
{
    std::string Key;
    float FloatData;

    virtual bool GetType() const override
    {
        return false;
    }
};

class SomeSystem
{

public:
    void Add(const FStructA& Struct)
    {
        //DataElements.push_back(std::shared_ptr<IStruct>(new FStructA(Struct)));
        DataElements.emplace_back(std::shared_ptr<IStruct>(new FStructA(Struct)));
    }

    void Add(const FStructB& Struct)
    {
        //DataElements.push_back(std::shared_ptr<IStruct>(new FStructB(Struct)));
        DataElements.emplace_back(std::shared_ptr<IStruct>(new FStructB(Struct)));
    }

    void Process()
    {
        for (std::shared_ptr<IStruct> DataElement : DataElements)
        {
            if (DataElement->GetType())
            {
                FStructA StructA = *static_cast<FStructA*>(DataElement.Get());
                // Process A
            }
            else
            {
                FStructB StructB = *static_cast<FStructB*>(DataElement.Get());
                // Process B
            }
        }
    }

private:
    std::vector<std::shared_ptr<IStruct>> DataElements;
};

Now as you can see I have already optimized on line, instead of push_back I am using emplace_back. This will definitely save some memory and increase speed but not that much. I don't think that's the answer to this question. There is definitely something else which I am missing.

Another point is overloaded Add function, I wanted to optimized it but I think its doing job correctly hence I am confused, where else can we optimized.

Kindly help me optimize this code.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire