C++ string stringstream 性能测试
对应字符串1、直接拼接;2、使用+=拼接;3、stringstream
代码如下
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <time.h>
#include <sstream>
using namespace std;
int main() {
struct timespec time_start = { 0, 0 }, time_end = { 0, 0 };
clock_gettime(CLOCK_REALTIME, &time_start);
string result;
// stringstream ss;
int num = 100000;
while (num--) {
// result = result + "test"; //直接拼接
result += "test"; // +=
// ss << "test"; // stringstream
}
// result == ss.str();
clock_gettime(CLOCK_REALTIME, &time_end);
int costtime = ((time_end.tv_sec-time_start.tv_sec)*1000000+(time_end.tv_nsec-time_start.tv_nsec)/1000);
cout << costtime << endl;
return 0;
};
测试环境为MacBook,测试num=10000数据如下:
类型 | 耗时us |
---|---|
直接拼接 | 8953 |
+= | 167 |
stringstream | 653 |
测试环境为MacBook,测试num=100000数据如下:
类型 | 耗时us |
---|---|
直接拼接 | 647472 |
+= | 1419 |
stringstream | 6531 |
结论
- 使用+=为直接拼接耗时的1/50;使用stringstream为直接拼接耗时的1/13。因此+=效果更好。
- 随时循环次数的增大,+=和stringstream耗时是对应倍数增加,但是直接拼接的耗时增大倍数更大,因此在字符串涉及较多的场景或循环场景,要避免使用直接拼接。
- 原因分析:直接字符串拼接 result = result + "test";会产生一个临时变量,从而导致耗时更高。
分类:
C++ 知识
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通