为了测试判断字符串为空的效率,今天特意做了一个测试。得出以下结论:
Cstring s = "我是一个中国人!";
s.GetLength() == 0 效率略快于 s.IsEmpty(),但是 s[0] == '\0' 效率比 GetLength() 低一倍。
换成 string 又测了一次:
//string s.length() 2730 毫秒
//string s.empty() 2839 毫秒
//string s[0] 5616 毫秒
结论:标准C++的 string 真让人失望,效率如此低下!!虽然 CString 受限于MFC,但还是值得首选!
最后又测了一次 char s[24] ="我是一个中国人!";
用 s[0] == '\0' 仅需时234毫秒,哈哈,还是C语言快啊!
// s.GetLength() == 0 效率略快于 s.IsEmpty()
// s[0] == '\0' 效率比 GetLength() 低一倍。
// 10亿次循环,s[0]需时1529毫秒, s.IsEmpty() 需时 874毫秒, s.GetLength() 用时 655 毫秒
DWORD start = GetTickCount();
CString s = "我是一个中国人!";
for (int i = 0; i <= 100000000; ++i)
{
if (s.GetLength() == 0) {
//if (s.IsEmpty()) {
//if (s[0] == '\0') {
CString b = s;
continue;
}
}
double end = GetTickCount() - start;
CString msg;
msg.Format("用时:%f", end);
AfxMessageBox(msg);