简体   繁体   English

宽字符串与字符串,它是否会影响Windows C ++中的性能

[英]Wide String vs String , Does it affect performance in Windows C++

I'm handling a lot of Unicode file paths in my C++ project. 我在C ++项目中处理了很多Unicode文件路径。 I peform a check in my code , if they are fine enough to fit in Multibyte String , i keep it as a normal string (std::string) variable,where else if the string doesn't fit in Multibyte i use it as a wide char string. 我在我的代码中执行检查,如果它们足够好以适合Multibyte String,则将其保留为普通字符串(std :: string)变量,否则,如果该字符串不适合Multibyte,则将其用作宽字符字符串。

My question is whether i can use the paths totally as wstrings ..? 我的问题是我是否可以完全将路径用作wstrings ..? would it affect performance, i have to do some string manipulations,file open, create,rename and delete with the wstring. 它会影响性能吗,我必须做一些字符串操作,使用wstring打开文件,创建,重命名和删除文件。 So rather that checking multibyte or wide char string, i would like to use it directly as wstring which would save me a lot of if/else. 因此,与其检查多字节或宽字符字符串,不如直接将它用作wstring,这样可以节省很多if / else。

bool IsUnicodeWString(const std::wstring &_WStr)
{
  WCHAR* posUnicodePath = (WCHAR*)_WStr.c_str();
  size_t multiByteLen = wcstombs(NULL, posUnicodePath, 0) + 1;
  int tempLength = 0;
  if (multiByteLen > 0)
  {
    TCHAR* _tmpTChar = new TCHAR[multiByteLen + 1];
    memset(_tmpTChar, '\0', multiByteLen + 1);
    tempLength = wcstombs(_tmpTChar, posUnicodePath, multiByteLen);
    if (tempLength == std::string::npos)
    {
      multiByteLen = 0;
    }
    delete[] _tmpTChar;
  }
  if(multiByteLen == 0 || multiByteLen == std::string::npos) { // Is Unicode file 
    return true;
  }
  else{
    return false;
  }
}

if(IsUnicodeWString) {
        // Use wstring [ Operations - String Manipulations,FilePath used for Open,Read,Write,Create,Delete,Rename,etc]
} else {
        //string  [ Operations - String Manipulations,FilePath used for Open,Read,Write,Create,Delete,Rename,etc]
}

Please share your thoughts ... 请分享您的想法...

In Windows, Try to use wchar_t as much as posible. 在Windows中,尝试尽可能多地使用wchar_t Because it is default character representation in Windows, kernel also using wchar_t as default. 因为它是Windows中的默认字符表示形式,所以内核也将wchar_t用作默认字符。 All of ANSI APIs are the wrapper of UNICODE APIs. 所有ANSI API都是UNICODE API的包装。 If you disassembly ANSI APIs, you will known the truth. 如果您反汇编ANSI API,您将了解真相。

Also, Use ATL::CString instead std::(w)string if possible. 另外,如果可能,请使用ATL::CString代替std::(w)string Because its used reference counting and the size of the class is equal to pointer size (4 bytes in 32-bits and 8 bytes in 64-bits). 因为它使用的引用计数和类的大小等于指针大小(32位为4个字节,而64位为8个字节)。 That mean you can return ATL::CString directly from the functions without performance penalty. 这意味着您可以直接从函数中返回ATL::CString ,而不会降低性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM