为什么我需要在每次迭代使用字符串流变量的循环时清除该变量
Why do I need to clear a stringstream variable with each iteration of a loop in which it is used
在我的学校,我们必须遵循一个风格指南,该指南规定我们必须在使用函数的顶部声明每个变量,而不是在使用之前。这通常意味着在循环中使用变量时必须重置或清除变量,因为它们不是在该循环中声明的。我不明白为什么字符串流变量需要在每次循环迭代中"清除",并希望有人可以阐明这一点。我知道如何清除它只是想知道为什么它是必要的。
这背后的基本原理是,在循环内创建重对象会导致性能下降。::std::stringstream
是这些对象之一,一直创建和销毁字符串流是一个常见的错误。但是,此类规则不适用于轻对象,例如基元类型。
考虑测试用例:
#include <chrono>
#include <sstream>
#include <iostream>
#include <cstdlib>
int main()
{
using namespace std;
using namespace chrono;
auto const loops_count{1000000};
auto const p1{high_resolution_clock::now()};
{
stringstream ss{};
for(auto i{loops_count}; 0 != i; --i)
{
ss.str(string{}); // clear
ss << 1;
}
}
auto const p2{high_resolution_clock::now()};
{
for(auto i{loops_count}; 0 != i; --i)
{
stringstream ss{}; // recreate
ss << 1;
}
}
auto const p3{high_resolution_clock::now()};
cout << duration_cast< milliseconds >(p2 - p1).count() << "ms "
<< duration_cast< milliseconds >(p3 - p2).count() << "ms"
<< endl;
return EXIT_SUCCESS;
}
第一个环路35ms,第二个环路 431ms
相关文章:
- 为什么我不能在不创建字符串变量的情况下使用函数的字符串输出
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 从字符串变量中逐字符读取单词
- 对函数 PlaySound 使用字符串变量
- C++中的字符串变量
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 如何使用C++将字符串中的字符转换为整数变量
- 字符串变量,比如说"字符串str",可以直接复制到数组中吗?
- 我可以用字符串变量而不是它的名字创建容器吗? C++
- 字符串变量的大小
- 使变量字符串忽略转义序列
- 如何在 C 宏中将变量字符串与文字字符串连接起来?
- 在 Py_BuildValue 中返回变量字符串
- 如何将字符串作为变量与另一个变量字符串进行比较
- 从变量字符串中提升文件系统路径
- 用变量字符串声明设置容器
- 通过变量(字符串)调用obejct和方法
- C++创建文本和变量字符串
- 如何在循环中使用变量字符串