3

为什么当我按如下方式填充 QVector 时:

QVector< QPair<qint32, QString> > vector(10000000);
QString temp;
for (int i = 0; i < 10000000; ++i)
{
   temp = QString::fromUtf8("Vasya");
   vector.replace(i, qMakePair(i, temp));
}

我的程序使用 470 MB 的 RAM,并且当这样:

QVector< QPair<qint32, QString> > vector(10000000);
QString temp2 = "Vasya";
for (int i = 0; i < 10000000; ++i)
{
    vector.replace(i, qMakePair(i, temp2));
}

它只有 90 MB 的 RAM?

4

1 回答 1

2

Because internally QString is optimized to share memory of const objects. First case needs allocate memory each time when fromUtf8 invoked. On opposite second case always can reuse memory from existing const temp2

于 2013-04-13T17:13:49.773 回答