读书人

连接字串的效率解决办法

发布时间: 2012-06-19 14:45:20 作者: rapoo

连接字串的效率
连接字串有很多方法,烦请比较效率
结果是要 C (const) char array.

1.

C/C++ code
int uid = 1234;const char name = "qpalz1";char str[128];sprintf(str, "%s%s%s%d", "My user name is ", name, ". Uid = ", uid);// str is the result


2.
C/C++ code
int uid = 1234;const char name = "qpalz1";char str[128];char cuid[10];sprintf(cuid, "%d", uid);strcpy(str, "My user name is ");strcat(str, name);strcat(str, ". Uid = ");strcat(str, cuid);// str is the result


3.
C/C++ code
int uid = 1234;const char name = "qpalz1";char cuid[10];sprintf(cuid, "%d", uid);std::string str = "My user name is " + name + ". Uid = " + cuid;// str.c_str() is the result


4.
C/C++ code
int uid = 1234;const char name = "qpalz1";std::stringstream stream;std::string str;stream << "My user name is " << name << ". Uid = " << uid;stream >> str;// str.c_str() is the result


还是有更好的办法?

[解决办法]
一般我们用的_snpsrintf()
C/C++ code
char buff[255] = {0};_snprintf(buff,sizeof(buff)-1,"%s%d","hello",1);
[解决办法]
考虑性能,要看瓶颈在哪里。不能任何事情都考虑效率,解决影响效率的关键点。像这种sprintf,又不是性能瓶颈,快一点慢一点无所谓的。
现在这社会,速度开发出东西才是王道
[解决办法]
写功能的时候不要过于考虑效率,写完以后再做 profile, 找出耗时间的地方再来修改
[解决办法]
strcat感觉已经是最快的了,微软的CRT也有一个汇编的实现。

当然,你不妨试试memcpy,这个应该和strcat一样快,这个也有汇编实现,C代码也差不多。总之,C库中的肯定是最快的,毕竟是几十年的老江湖了,能优化的肯定优化到极限了。sprintf涉及到格式,肯定不会是最快,C++的经过了层层封装,应该有额外的开销,应该不是最快的。

最好的办法是楼主在关掉全部优化的情况下,自己测试一下。
[解决办法]

http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express
右边Visual C++ 2010 Express下面的Select language...下拉选‘简体中文’,再按Install Now按钮


C:\Program Files\Microsoft Visual Studio 10.0\VC\crt\src\intel\strcat.asm

读书人网 >C++

热点推荐