strsafe functions performance

drjackool 956 Reputation points
2021-08-28T08:39:55.65+00:00

hi
strsafe.h functions do more checks to do string operations so I think standard string functions is faster is this correct? or should I use strsafe functions?
thanks

Windows API - Win32
Windows API - Win32
A core set of Windows application programming interfaces (APIs) for desktop and server applications. Previously known as Win32 API.
2,741 questions
{count} votes

2 answers

Sort by: Most helpful
  1. drjackool 956 Reputation points
    2021-08-28T16:03:51.49+00:00

    I used following code to measure speed and I post result:

    TCHAR buffer[1024];  
    LPCTSTR pszText = _T("This is sample text. This is sample text. This is sample text. This is sample text. This is sample text.");  
    
    LARGE_INTEGER start[4] = { 0 };  
    LARGE_INTEGER end[4] = { 0 };  
    
    QueryPerformanceCounter(&start[0]);		  
    for (UINT i = 0; i < 10000; i++)  
    {  
    	_tcscpy(buffer, pszText);  
    }	  
    QueryPerformanceCounter(&end[0]);  
    
    
    QueryPerformanceCounter(&start[1]);  
    for (UINT i = 0; i < 10000; i++)  
    {  
    	_tcscpy_s(buffer, 1024, pszText);  
    }  
    QueryPerformanceCounter(&end[1]);  
    
    QueryPerformanceCounter(&start[2]);  
    for (UINT i = 0; i < 10000; i++)  
    {  
    	lstrcpy(buffer, pszText);  
    }  
    QueryPerformanceCounter(&end[2]);  
    
    QueryPerformanceCounter(&start[3]);  
    for (UINT i = 0; i < 10000; i++)  
    {  
    	StringCchCopy(buffer, 1024, pszText);  
    }  
    QueryPerformanceCounter(&end[3]);  
    
    CString str;  
    str.Format(_T("_tcscpy(): %I64u\n_tcscpy_s(): %I64u\nlstrcpy(): %I64u\nStringCchCopy(): %I64u"),   
    	end[0].QuadPart - start[0].QuadPart,  
    	end[1].QuadPart - start[1].QuadPart,  
    	end[2].QuadPart - start[2].QuadPart,  
    	end[3].QuadPart - start[3].QuadPart);  
    MessageBox(0, str, _T("Result") , MB_OK | MB_ICONINFORMATION);  
    

    Results: (in 4)
    127287-untitled.png

    tcscpy() has best speed and StringCchCopy() has worste


  2. silverz 0 Reputation points
    2025-03-05T11:22:27.1233333+00:00

    For me, the results are as the following for 1'000'000 loop (Ryzen 5600x, Debug build):

    auto start = std::chrono::steady_clock::now();
    for (std::size_t i = 0; i < 1'000'000; ++i) {
        //StringCchCopy(lpszCurrentVariable, BUFSIZE, TEXT("MySetting=A")); // 32ms
        auto r1 = wcscpy(lpszCurrentVariable, TEXT("MySetting=B"));         // 42ms
    }
    using namespace std::chrono; // NOLINT(google-build-using-namespace)
    std::cout << std::format("Elapsed in XX : {:d}ms\n",
                             duration_cast<milliseconds>(steady_clock::now() - start).count());
    

    For Release builds, both are 0ms.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.