请教C风格字符串和标准string的性能、内存占用对比
各位好,首次在C++区提问,请多指点。
如题,本人觉得应该是C风格字符串在效率和内存占用上都占优,因为string本身就是将C字符串进行了封装。
于是,做了如下测试,请大家参考数据。
注:发现,字符串越长,string的性能相对越好!
并请研究过这方面的行家指点一下:二者在性能和内存占用真正的对比。
VC2003的Release模式下:
代码①:
C-style string run 10000000 times needs 3144 clock times
C++ string run 10000000 times needs 3966 clocks
代码②:
C-style string run 10000000 times needs 2914 clock times, error:0
C++ string run 10000000 times needs 1772 clocks, error:0
代码③:
如果把代码②中的size_t size = lstrlen(pc2);和size_t size = str2.size();都注释掉,则
C-style string run 10000000 times needs 2113 clock times, error:0
C++ string run 10000000 times needs 1622 clocks, error:0
代码①:
#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= "我想用VC编写一个界面, ";
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 = pc;
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 0;
}
代码②:
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
const size_t retime=10000000;
int main()
{
clock_t start, finish;
start=clock();
const wchar_t *pc=L "请教C风格字符串和标准string的性能 ";
size_t error = 0;
const size_t len = lstrlen(pc);
wchar_t *pc2= new wchar_t[len+1];
for(size_t ix=0; ix!=retime;++ix)
{
lstrcpy(pc2,pc);
size_t size = lstrlen(pc2);
if(lstrcmp(pc2,pc)) error++;
}
delete []pc2;
finish=clock();
cout < < "C-style string run " < <retime < < " times needs " < <finish-start < < " clock times, error: " < < error;
cout < <endl;
error = 0;
start=clock();
wstring str = pc;
wstring str2;
for(size_t ix=0;ix!=retime;++ix)
{
str2=str;
size_t size = str2.size();
if(str!=str2) error++;
}
finish=clock();
cout < < "C++ string run " < <retime < < " times needs " < <finish-start < < " clocks, error: " < < error;
cout < <endl;
return 0;
}
[解决办法]
注:发现,字符串越长,string的性能相对越好!
显然
[解决办法]
我觉得最好的办法还是去了解一下string的实现,不同的实现性能和内存肯定会有差异的。
当涉及到string之间的赋值时,使用的可能是copy-on-write技术,显然要比c风格字符串的性能要好。
[解决办法]
呵呵,还是觉得使用string好.
[解决办法]
管这么多干什么,你应该在乎的是程序的正确性和可维护性,不是这点算来算去算不明白的性能。
[解决办法]
看着不像,但是STL真的很好。
[解决办法]
你多换几个编译器,完全可能得到相反的结论。
string不是因为效率的原因来取代char *的。
而是因为易用性方面的提高。