首页 > 解决方案 > QString 和 QByteArray 内存使用情况

问题描述

QByteArray 文档声明它在内存保护至关重要时使用。我一直在研究一个类 (FieldName),它保留常用 QString 的内部存储,以便在比较两个 FieldName 对象是否相等时,完成快速整数比较。

我的想法是我可以通过使用 QByteArray 而不是 QString 来节省一些内存并提高速度,因为我只需要标准的 ASCII 字符。但是当我在下面的代码中为 QByteArray 更改 QString 时,我的测试表明速度提高了,但内存使用量增加了一倍以上。这与文档背道而驰。

#ifndef H_FIELDNAME
#define H_FIELDNAME

#include <QString>

class FieldName
{
   public:
      FieldName() : mKey(0) { init(); }
      FieldName(const QString& s);
      const QString& constString() const;
      bool operator==(const FieldName& other) const { return mKey == other.mKey; }
      bool operator!=(const FieldName& other) const { return mKey != other.mKey; }
   private:
      int mKey;
      void init();
      int findKey(const QString& s);
};

#endif

CPP 文件:

#include "fieldname.h"
// #include <QMutex> // demo version not thread-safe
#include <QVector>

static QVector<QString*> FieldName__List;
static bool FieldName__FirstCall(true);

FieldName::FieldName(const QString& s)
{
   init();
   mKey = findKey(s);
}

const QString& FieldName::constString() const
{
   return(*FieldName__List.at(mKey));
}

void FieldName::init()
{
   if(FieldName__FirstCall)
   {
      if(FieldName__List.isEmpty())
      {
         FieldName__List.append(new QString(""));
         FieldName__FirstCall = false;
      }
   }
}

int FieldName::findKey(const QString& s)
{
   if(s.isEmpty())
      return 0;
   int sz(FieldName__List.size());
   for(int idx=1; idx<sz; ++idx)
   {
      if(s == *FieldName_List.at(idx))
         return idx;
   }
   FieldName__List.append(new QString(s));
   return(FieldName__List.size() - 1);
}

当我在上面的类中用 QByteArray 代替 QString 时,谁能告诉我我可能在做什么导致这使用更多内存?

测试代码:

QStringList qsl; // filled with 84000 unique English words
FieldName fn;
foreach(QString s, qsl)
{
   fn = FieldName(s);
   // do stuff here
}

标签: c++qt

解决方案


推荐阅读