C风格字符串和std string风格字符串效率?
一直以来,我都认为C风格的字符串处理起来效率高。今天看书C++ Primer的时候才发现原来std string风格的字符串比C风格字符串的效率高了不是一点点啊!!
请大牛现身讲讲原理吧。我个人之前以为C风格字符串就是一个数组,内存中连续排列,应该很快。
而std string的字符串,是一个类,每次使用还要构造、析构一番。虽然是自动的,但是应该费时啊。所以尽量使用C风格字符串。好像我们公司的人,也基本都是有C风格字符串。上次写东西用了std string还被小小鄙视了一下。
// C-style character string implementation
const char *pc = "a very long literal string";
const size_t len = strlen(pc +1); // space to allocate
// performance test on string allocation and copy
for (size_t ix = 0; ix != 1000000; ++ix) {
char *pc2 = new char[len + 1]; // allocate the space
strcpy(pc2, pc); // do the copy
if (strcmp(pc2, pc)) // use the new string
; // do nothing
delete [] pc2; // free the memory
}
// string implementation
string str("a very long literal string");
// performance test on string allocation and copy
for (int ix = 0; ix != 1000000; ++ix) {
string str2 = str; // do the copy, automatically allocated
if (str != str2) // use the new string
; // do nothing
}
// str2 is automatically freed
还慢呢。
[解决办法]
看来以后啊,要尽量利用库函数去写代码,编译器对它们的优化可不得了。
[解决办法]
std::string效率高的原因是使用了引用计数,其实是不公平的对比。
如果不使用引用计数的话,要比C风格字符串的效率低的多。
[解决办法]
以下链接供参考:
http://topic.csdn.net/t/20060423/22/4707818.html
http://topic.csdn.net/u/20070705/09/2a5034a0-0930-4daa-932d-16b62b107c87.html
http://www.ecjtu.org/forum/read.php?tid-20787-uid-51602.html
[解决办法]
引用计数效率虽高,但有致命缺陷:线程不安全
ATL 9 的CString就没有使用引用计数,所以其效率比C风格字符串要低不少。
[解决办法]
这个要看你具体使用时,大部分时间是用string在做什么了。如果你狂在那里拷贝,那么使用了引用计数的string自然快很多。
如果你狂在那里修改字符串,那么C-style的string会高效一些
[解决办法]
http://hi.baidu.com/mefirst/blog/item/561a5c0a5bbce23bb0351d61.html
可以参考
[解决办法]
应该主要考虑开发效率吧,那点运行时间算得了什么。