jeudi 21 novembre 2019

I created a library and was wondering if the design is inefficient

In the design of my library I construct a lot of objects and was wondering if this will cause it to be inefficient.

I created a library the creates and runs a query. The query is a class that takes an rvalue reference to a initializer_list of Bind objects. Each Bind takes some value.

I'm thinking that the design is inefficient because each Bind object is going to be making a copy of its value except for strings if we use const char*s. On top of that we have to construct an entire Bind object for each of those values. I then round all the Binds up into an initializer_list and move them into a vector which I'm not sure how much overhead there is there. This is created in the Query object which might not be that expensive to construct and only one Query object is created.

Looking at the main function at the bottom of the code snippet might be all you need to look at.

class Database {
public:
    Database() = default;
    ~Database() = default;
    Result run(Query&& query);    
};

class Query {
public:
    Query(const char* query, std::initializer_list<Bind>&& binds);
    ~Query() = default;

    ...

private:
    std::string m_query;
    std::vector<Bind> m_binds;
};

Query::Query(const char* query, std::initializer_list<Bind>&& binds) : m_query(query), m_binds(binds) {}


class Bind {
    friend Query;
public:
    explicit Bind(int32_t i);
    explicit Bind(int64_t i);
    explicit Bind(uint32_t i);
    explicit Bind(float f);
    explicit Bind(const char* str);

private:
    int bind(sqlite3_stmt* stmt, int column);

    ColumnType m_type;
    union {
        int64_t m_i;
        float m_f;
        const char* m_str;
    };
    size_t m_str_size;
};

int main()
{
    Database db;
    auto result = db.run(Query(
        "INSERT INTO users VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        Bind(id),
        Bind(first_name),
        Bind(last_name),
        Bind(age),
        Bind(height),
        Bind(weight),
        Bind(siblings),
        Bind(hometown),
        Bind(mom),
        Bind(dad),
        Bind(num_pets),
        Bind(os::time_since_epoch()),
        Bind(location),
        Bind(json),
    }));
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire