bloguetronica / cp2130-qt

A C++ class that uses libusb to interface with CP2130 devices. It can be used to configure the OTP ROM of such devices, as well as to control them. The class was made for Qt. If you wish to use a derived non-Qt version, please refer to https://github.com/bloguetronica/cp2130.
0 stars 0 forks source link

Unnecessary append operations in "cp2130.cpp", line 937 #30

Closed samuelfmlourenco closed 2 years ago

samuelfmlourenco commented 2 years ago

Inside the file "cp2130.cpp", in line 937, there is an instance where values from writeReadInputBuffer are appended to retdata. An excerpt of spiWriteRead(), the function which contains said line, follows:

// Writes to the SPI bus while reading back, returning a vector of the same size as the one given
// This is the prefered method of writing and reading, if both endpoint addresses are known
QVector<quint8> CP2130::spiWriteRead(const QVector<quint8> &data, quint8 endpointInAddr, quint8 endpointOutAddr, int &errcnt, QString &errstr)
{
    size_t bytesToWriteRead = static_cast<size_t>(data.size());
    size_t bytesLeft = bytesToWriteRead;
    QVector<quint8> retdata;
...
        int bytesRead = 0;  // Important!
        bulkTransfer(endpointInAddr, writeReadInputBuffer, payload, &bytesRead, errcnt, errstr);
        for (int i = 0; i < bytesRead; ++i) {
            retdata += writeReadInputBuffer[i];
        }
...
    return retdata;
}

However, appending to a QVector is slower than just assigning a value to an element that already exists. Once the number of bytes read is known, retdata could be resized and then the values assigned to it:

// Writes to the SPI bus while reading back, returning a vector of the same size as the one given
// This is the prefered method of writing and reading, if both endpoint addresses are known
QVector<quint8> CP2130::spiWriteRead(const QVector<quint8> &data, quint8 endpointInAddr, quint8 endpointOutAddr, int &errcnt, QString &errstr)
{
    size_t bytesToWriteRead = static_cast<size_t>(data.size());
    size_t bytesLeft = bytesToWriteRead;
    QVector<quint8> retdata;
...
        int bytesRead = 0;  // Important!
        bulkTransfer(endpointInAddr, writeReadInputBuffer, payload, &bytesRead, errcnt, errstr);
        retdata.resize(bytesRead);
        for (int i = 0; i < bytesRead; ++i) {
            retdata[i] = writeReadInputBuffer[i];
        }
...
    return retdata;
}
samuelfmlourenco commented 2 years ago

Implemented in version 2.2.2.