如何通过只加载用户需要的内容来最大限度地提高字符串的效率
How can I maximize efficiency of strings by only loading what the user needs?
我正在编写一个程序,它的设置如下:
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"结构的方法。
相关文章:
- 操作顺序以最大限度地提高精度
- 在高数据包速率下最大限度地减少丢弃的 UDP 数据包 (Windows 10)
- 我是否需要遍历升压 rtree 的层次结构才能实现最大效率?
- 模棱两可的功能超载[例如最大限度()]
- 如何最大限度地减少使用标量 SIMD 内部函数的 SIMD 注册表的双重负载开销
- 如何通过只加载用户需要的内容来最大限度地提高字符串的效率
- 通过ARM NEON程序集最大限度地优化元素乘法
- CUDA:最大限度地减少大型数据类型的银行冲突
- 工具来帮助最大限度地减少C++程序中宏的使用
- 如何最大限度地使用数字0来优化程序
- 如何最大限度地减少来自 arduino 的串行通信读取错误
- Unodered_map找到,然后放置或只是插入以获得最大效率
- 如何在最大限度地提高大小有效性的同时,将3态的位运算符实现为任何大小的内存
- Windows c++如何最大限度地启动应用程序
- BerkeleyDB最大限度地提高性能和减少数据丢失
- 在std容器上执行一系列操作时,最大限度地减少峰值内存使用
- 最大限度地理解子阵列_问题
- 如何优化VBO/IBO以最大限度地利用GPU缓存
- 使用 Boost 的 file_mapping 和mapped_region最大限度地减少内存使用?
- 最大限度地提高孩子的幸福感