Reputation: 805
Both of these functions fill the TCHAR sStringA and sStringB. The question is which one is preferred and more efficient in returning a result?
#include <tchar.h>
#include <Windows.h>
void FunctionA(TCHAR *sString1, DWORD dwLen)
{
_tcscpy_s(sString1, dwLen, L"String1");
return;
}
void FunctionB(TCHAR **sString2, DWORD dwLen)
{
*sString2 = (TCHAR*)calloc(dwLen, sizeof(TCHAR));
_tcscpy_s(*sString2, dwLen, L"String2");
return;
}
int main()
{
TCHAR *sStringA = (TCHAR*)calloc(100, sizeof(TCHAR));
TCHAR *sStringB = NULL;
FunctionA(sStringA, 100);
FunctionB(&sStringB, 100);
free(sStringA);
free(sStringB);
}
From my comment below, here is FunctionC:
void FunctionC(TCHAR **sString2, DWORD dwLenOut)
{
TCHAR sString[] = L"String2";
dwLenOut = (DWORD) _tcslen(sString) + 1;
*sString2 = (TCHAR*)calloc(dwLenOut, sizeof(TCHAR));
_tcscpy_s(*sString2, dwLenOut, sString);
return;
}
int main()
{
TCHAR *sStringC = NULL;
DWORD dwLen = 0;
FunctionC(&sStringC, dwLen);
}
Upvotes: 1
Views: 53
Reputation: 180161
It is highly unlikely to be any more costly to pass a pointer to a pointer than it is to pass a pointer to a TCHAR
. The only significant difference between your two alternatives, performance-wise, is that B performs one extra address-of (&
) and one dereference (unary *
) operation, and although that makes B a tiny bit more costly in principle, the difference is unlikely to be noticeable.
Of course, the compiler could optimize the two calls to exactly the same code. It might even optimize away the calloc()
calls, though that's less likely.
Overall, it is unlikely to be worth your time to focus on micro-optimizations of this sort, unless possibly you've determined, by measurement, that the section of code containing them is too slow, and you cannot find an algorithmic improvement, and you've reason to believe that the specific operations you're trying to optimize make a significant contribution to that code's cost.
Upvotes: 3
Reputation: 13890
FunctionA
is slightly is more efficient, because it does less dereferencing.
Upvotes: 0