Friday, June 17, 2005

29. How can I write the most efficient code when using HBufC?

(1) Spawn HBufC from existing descriptors using TDesC::AllocL() rather than creating and copying into them

HBufC can be spawned from a existing descriptor using the Alloc() or AllocL() overloads of by TDesC. You can thus replace code like this:

void SomeFunctionL(const TDesC& aDes)
{
HBufC* heapBuffer = HBufC::NewL(aDes.Length());
TPtr ptr(heapBuffer->Des());
ptr.Copy(aDes);
...
}

With the more efficient single line:

void SomeFunctionL(const TDesC& aDes)
{
HBufC* heapBuffer = aDes.AllocL();
...
}

(2) Don't call HBufC::Des() if you need only non-modifiable access to the data

It is clearer and more efficient simply to dereference an HBufC if you need a non modifiable reference to its data. You only need to call Des() when you need to modify it - Des() will return a TPtr. That is:

void Log(const TDesC& aLogBuf); // Forward declaration
void Convert(TDes& aBuf);

void CMyClass::SomeFunction()
{// iHeapBuf is a member of CMyClass
// Get non-modifiable access (TDesC&) to iHeapBuf
Log(*iHeapBuf); // Call a method which takes const TDesC&

// Now get modifiable access (TDes&) to iHeapBuf
Convert(iHeapBuf->Des()); // Call a method which takes TDes&

}


By the way, an interesting side-effect of creating a modifiable descriptor from a non-modifiable heap descriptor is discussed in Tip 9.

This page is powered by Blogger. Isn't yours?

Google
WWW Descriptors FAQ