Search code examples
c++stringconcatenationstring-concatenation

Fastest and/or safest way to concatenate two wide strings in c++?


Is one of the following wide string concatenation methods faster and/or safer than the other?

1) std::wstring

LPCWSTR str1 = L"string 1,";
LPCWSTR str2 = L"string 2";

std::wstring stdResult = std::wstring(str1) + str2;
LPCWSTR result = stdResult.c_str();

2) wcscpy_s, wcscat_s

WCHAR buf[128];

LPCWSTR str1 = L"string 1,";
LPCWSTR str2 = L"string 2";

wcscpy_s(buf, str1);
wcscat_s(buf, str2);
LPCWSTR result = buf;

3) _snwprintf_s

WCHAR buf[128];

LPCWSTR str1 = L"string 1,";
LPCWSTR str2 = L"string 2";

_snwprintf_s(buf, _TRUNCATE, L"%s%s", str1, str2);
LPCWSTR result = buf;

or is there a faster/safer method?

Of these, what is the best option in terms of:

  • Speed
  • Security

Solution

  • The examples are not proper. For example, in your wcscat variation, there is no additional memory allocation, so it is as rapid as it will ever get.

    When doing a += on a std::wstring, speed mostly depends on whether std::wstring will have to reallocate.

    Therefore, your problem reduces to the memory allocation issue. If there is memory allocated already, then wstring should perform as fast as you would need.

    The other issue is what others have noticed already, that you want reasonable speed and maximum safety. If you plan on too many concatenations and your profiler shows significant speed issues, then you can implement your own allocator.