C风格字符串和C++ string 对象赋值操作的性能比较

<<C++ Primer>> 第四版 Exercise Section 4.3.1 部分Exercise 4.2.9 习题如下:

在自己本机执行如下程序,记录程序执行时间:

 

 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <string>
 4 #include <vector>
 5 #include <ctime>
 6 
 7 using namespace std;
 8 
 9 int main()
10 {
11     clock_t start, end;
12     start = clock();
13     const char *pc = "a very long literal string";
14     const size_t len = strlen(pc);
15     cout << "the length of pc is: " << len << endl;
16     for (size_t ix = 0; ix != 10000; ++ix)
17     {
18         char *pc2 = new char[len+1];
19         strcpy_s(pc2,len+1,pc);
20         if (strcmp(pc, pc2))
21         {
22             // do nothing
23         }
24         delete[] pc2;
25     }
26 
27     end = clock();
28     cout << "for c style operation : " << (end - start) << endl;
29 
30     clock_t start1, end1;
31     start1 = clock();
32     string str("a very long literal string");
33     for (int ix = 0; ix != 10000; ++ix)
34     {
35         string str2 = str;
36         if (str != str2)
37         {
38 
39         }
40     }
41     end1 = clock();
42     cout << "for c++ string operation : " << (end1 - start1) << endl;
43     return 0;
44 }

 

其中时间记录的代码是我自己加的,用于分别记录C风格字符串和C++ string对象赋值操作的执行时间。执行结果如下:

 

 c++ string 对象的赋值操作耗时明显比c风格字符串要长很多,但是从书上的结论来说,c++ string的操作要远比c风格字符串长。所以这里记录下,以后研究标准库时,分析代码来找原因。

 

转载于:https://www.cnblogs.com/lucy-lizhi/p/6476710.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值