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";会产生一个临时变量,从而导致耗时更高。
posted @ 2022-09-27 16:41  小海哥哥de  阅读(342)  评论(0编辑  收藏  举报