C风格字符串与标准库string类型性能对比

  今天在看c++ primer书中挺到C风格字符串与标准库string类型的效率问题。推荐使用string类型,不但因为其更安全,且因其效率更高。最后有提到一个数据。
  “平均来说,使用string类型的程序执行速度要比用C风格字符串的快很多,在我们用了五年的PC机上其平均执行速度分别是:
  user   0.47    #string class
        user   2.55    #C-style haracter string”
  对这个数据表示相当的惊讶。于是自已写了个程序,测试一下两个类型的效率。
#include  < iostream >
#include 
< string >
#include 
< ctime >
using   namespace  std;
const  size_t retime = 1000000 ;
int  main()
{
    clock_t start, finish;
    start
=clock();
    
const char *pc="a very long literal string";
    
const size_t len = strlen(pc);
    
for(size_t ix=0; ix!=retime;++ix)
    
{
        
char *pc2= new char[len+1];
        strcpy(pc2,pc);
        
if(strcmp(pc2,pc))
          ;
        delete []pc2;
    }

    finish
=clock();
    cout
<<"C-style string run "<<retime<<" times needs "<<finish-start<<" clock times";
    cout
<<endl;

    start
=clock();
    
string str("a very long literal string");
    
for(size_t ix=0;ix!=retime;++ix)
    
{
        
string str2=str;
        
if(str!=str2)
          ;
    }

    finish
=clock();
    cout
<<"C++ string run "<<retime<<" times needs "<<finish-start<<" clocks";
    cout
<<endl;
    
return ;

}

  上述程序在CentOS下编译并运行测试得数据平均在:
C-style string run 1000000 times needs 240000 clock times
C++ string run 1000000 times needs 110000clocks
在这个数据下明显string的效率要高。
  而在windows下使用vc6.0 release编译并运行,数据平均在:
C-style string run 1000000 times needs 350 clock times
C++ string run 1000000 times needs 350 clocks
  两种类型的效率差不多
  继续在vs2005下release编译,数据平均在:
C-style string run 1000000 times needs 320 clock times
C++ string run 1000000 times needs 370 clocks
  string效率要低一个。
在Linux平台下,string的效率比C-style的要整整高出一倍有多。
而在windows平台下,sting不但效率上的优势没有了,反而比C-style还要差。
不知道这是什么原因。为什么在unix下要比在windows下快如此的多。而在windows上却不行?
快的原因在哪呢?
PS:
不知道我的测试程序这样子写是否可以。

你可能感兴趣的:(C风格字符串与标准库string类型性能对比)