Subj : Re: OO compilers and efficiency To : comp.programming From : sebasttj Date : Fri Jul 22 2005 07:05 am websnarf@gmail.com wrote: > Here's a trick I'd like to see "improved C++ code" for (requires > bstrlib, which can be found at http://bstring.sf.net/): > > /* The C++ way */ > a = CBString ("end"); > for (i=0; i < 100000; i++) { > a = CBString (&tbstrTable[i%8]) + a; > } a = CBString("end"); for(int i=0; i!=100000; ++i) { CBString t(&tbstrTable[i%8]); t += a; swap(t, a); } And code a swap function for CBString along the lines of the one for the STL containers (ie, O(1) time). > But the reason that C is superior here is that it doesn't rely on > implicit storage for the base of the object. The "a = b" line, just > does a pointer assignment, which essentially just swaps the object > base. The reason your C++ version sucked is because you didn't provide and use a swap function (which, as you said in the quote, is the operation you wanted). You were using value-semantics assignment as a replacement, but it does a *lot* more work than you needed. > A similar case is for block initialization. STL's vectors, for > example, requires individual constructing of each element as the vector > grow, including empty constructors for "anticipated elements". No, they don't. Memory is allocated (usually using operator new, the C++ equivalent of malloc -- no constructors are called) in anticipation of future elements, but they aren't constructed (using placement new) until they're actually needed. > A > comparable implementation in C can just malloc big blocks of pointers > and set them all to NULL in a single for-loop or memset or whatever. Then the C++ version is more efficient, because it doesn't need to do the memset. :-) > This also applies to the creation of complicated data structures, say, > like tries. In C you can make "custom allocators" which will allocate > many nodes at once in a single malloc Wow... I wish someone on the C++ standardization committee had thought of custom allocators. /sarcasm > Perhaps there is something fundamental about C++, or OO in general that > I am not understanding, but how does C++ address this? It looks to me like you just don't know C++ very well. Most people don't. (Not that I do, either.) Josh .