Monday, 13 February 2017

BSTRs should be treated as data exchange format, hence no LTrim for BSTR

So, VBA uses COM types and the string is in fact a BSTR.  There are a whole multitude of C/C++ string types and string classes because of the 8 bit/16 bit baggage and various libraries such as MFC, ATL and STL.  One wonders how best to interact with a BSTR.

One also wonders why a BSTR does not come with its own functions such as trim etc.  Here, I can quote an exchange on this subject at http://computer-programming-forum.com/77-vc-atl/5b5e3637cb0be00e.htm.

P.S. Very ruefully that neither _bstr_t nor CComBSTR doesn't support real string interface with [R|L]Trim, SubString, UpperCase and others.
to which is given an extremely interesting reply
There is a very good reason for this. Most of those operations cannot be performed in-place, you need to reallocate memory. And allocating a BSTR is expensive, since it must come from task memory allocator that is known to be slow. If you need to perform string manipulations, it is recommended to convert a BSTR to your favorite string class, perform string manipulations with it, and only allocate a new BSTR when you need to return the string to the client or something like that. In other words, BSTRs should be treated as data exchange format, not as general-purpose string representation and manipulation format. Reduce the operations on them to a minimum.
wow, "BSTRs should be treated as data exchange format", very interesting.

Ok so the MSDN article on Programming with CComBSTR (ATL) also gives a similar warning 
As the CComBSTR class allocates a buffer to perform certain operations, such as the += operator or Append method, it is not recommended that you perform string manipulation inside a tight loop. In these situations, CStringT provides better performance.
So it seems Microsoft are tipping CStringT as a good class for Unicode and lo and behold this class has a Trim function CStringT::Trim

No comments:

Post a Comment