c++ - 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
}
解决方案
推荐阅读
- powershell - Powershell 表和计数
- python - 如何在 django rest 框架中的用户注册上使用 validate_password 函数?
- php - 什么会导致 laravel 刀片模板无法处理?
- javascript - 过滤多层嵌套数组
- ios - 多用户项目匹配会话数据库设置 - iOS Firebase Firestore
- r - 读取 CSV 文件并在 lapply 表达式中删除 BOM
- python - 如何用漂亮的汤将图像提取到数据框中?
- javascript - 为里面的画布和图像数据创建一个“相机”组件
- python - 从 2 个 python 脚本中检索数据
- python - 在 Pandas 中聚合行