如何优化这个toString()成员函数?

时间:2017-06-12 23:44:22

标签: c++

我有一个Vector2D对象,它返回当前坐标的字符串表示形式,称为Vector2D::toString()。由于Vector2D::toString()可能经常被调用,我想知道是否有更快的方法来返回一串坐标。

string Vector2D::toString()
{
    char buffer[64];
    int length;

    sprintf_s(buffer, 64, "(%.2f, %.2f)", m_x, m_y);

    return string(buffer, strlen(buffer));
}

我觉得这样做太多了,但我错了。如何优化?

更新:

string Vector2D::toString()
{
    static char buffer[64];
    static int length;

    length = sprintf_s(buffer, 64, "(%.2f, %.2f)", m_x, m_y);

    return string(buffer, length);
}

1 个答案:

答案 0 :(得分:1)

您可以实现另一个允许传入string&的版本,以便它将写入预先分配的字符串缓冲区。这可以防止string构造函数每次都必须复制char缓冲区。如果容量太小,您需要支付调整大小的罚款,但如果您反复调用toString,则只需要实际重新分配一次,之后相同的string每次都有足够的容量

我的理解是,如果resize小于capacity,std :: string通常不会降低其容量。从技术上讲,具体实现是否向下调整大小是否会导致重新分配,但您可以自己测量它以验证它是否正常运行。

这是我脑海中想到的一个草图。对不起,如果有任何错误。随意删除任何中间变量 - 我主要将它们留在那里以便于阅读。

void Vector2D::toString(const string& strBuffer)
{
    const int requiredCapacity = 50;
    strBuffer.resize(requiredCapacity);
    int writtenLength = sprintf_s(strBuffer.data(), requiredCapacity, "(%.2f, %.2f)", m_x, m_y);
    strBuffer.resize(writtenLength);
}

示例:

string myString;
// I'm making some guesses as to your Vector2D implementation for example purposes
Vector2D myVector(1, 0);

myVector.toString(&myString);
// myString now contains "(1, 0)" and a \0 so size() should return 7,
// capacity() should return at least 50 because of the initial resize()
// inside toString. It will probably be more because of the allocator's
// behavior.

myVector.set(1.3847, 2.3881);
myVector.toString(&myString);
// myString now contains "(1.3847, 2.3881)" and a \0, but it likely did
// not need re-allocation because it already had enough capacity from the
// first time around.