如何通过只加载用户需要的内容来最大限度地提高字符串的效率

How can I maximize efficiency of strings by only loading what the user needs?

本文关键字:最大限度 效率 字符串 何通过 加载 用户      更新时间:2023-10-16

我正在编写一个程序,它的设置如下:

struct element {
std::string two_very;
std::string long_strings;
};
struct set {
std::string name;
element e1;
...
element e12;
};

class myClass
{
public:
set *which_set;
};
set set1, set2, set3, set4;

int main(int argc, char *argv[])
{
myClass stuff;
for (int i = 0; i < argc; i++) {
std::string choice(argv[i]);
if (choice == set1.name) {
myClass.which_set = &set1;
} else if (choice == set2.name) {
}
}

这些字符串很长,我不想让它们同时出现在记忆中。但是,用户一次只能使用其中一个set结构,那么有没有办法只加载用户需要的结构?

您可以将字符串存储在一个文件中,并且只有在请求时才实际读取内容。

更确切地说,将结构转换为类并移除成员变量。给它两个成员函数:GetString1()GetString2()。缓存结果的私有字符串成员变量+私有int成员变量(在这个具体例子中没有更好的机制),以记住缓存当前代表的两个字符串中的哪一个。

class element {
public:
element();
std::string GetString1() const;
std::string GetString2() const;
private:
int mutable m_cache_for_which_string; // made mutable for const methods 
std::string mutable m_cache; // made mutable for const methods
};

当调用GetString1()时,如果第一个字符串不在缓存中,则打开包含该字符串的文件;对于具有第二字符串的CCD_ 5也是如此。您可以通过将其中任意一个字符串存储在m_cache成员变量中来记住它。

std::string element::GetString1() const
{
if (m_cache_for_which_string != 1)
{
std::ifstream is("file1.txt");
// ...
m_cache_for_which_string = 1;
m_cache = file_contents;
}
return m_cache;
}
std::string element::GetString2() const
{
if (m_cache_for_which_string != 2)
{
std::ifstream is("file2.txt");
// ...
m_cache_for_which_string = 2;
m_cache = file_contents;
}
return m_cache;
}

当然,构造函数需要初始化m_cache_for_which_string:

element::element() :
m_cache_for_which_string(0), // neither
m_cache()
{}

并且读取文件的代码不应重复。

整个技巧确保了内存中同时只有一个字符串,同时提供了一个隐藏这些细节的接口。返回值优化(RVO)应确保按值返回字符串不会影响性能(否则,当测量结果表明RVO不起作用时,您可以始终返回std::string const&,再次测量,如果速度更快,则保留它)。

这里有最后一个提示:您可能想阅读更多关于std::map的信息,并使用它来代替具有"name"成员变量的"set"结构的方法。