[Effective-cpp] Item 1: Uses and Abuses of vector
Timothy C. Wright
tim at tcw321.com
Tue Oct 26 22:59:53 EDT 2004
>Tim,
>
>you did a great job. It and this discussion certainly set the bar fairly
>high.
>
>
Thanks
>I would like to add to the summary two bits that have been overlooked up to
>now.
>
>4. (p. 6) avoid unecessary recalculations. This is pertinent in a for loop.
>If the for loop has this structure:
>
>for (vector<int>::const_iterator it = vint.begin(); it != vint.end(); ++ it
>)
>
>the value of vint.end() has to be calculated each time through the loop. On
>small vectors this would have no appreciable effect, but for very large
>vectors, and I would guess for vectors of fairly complicated data
>structures, the overhead of this recalculation could be quite significant.
>I like the advice to calculate the value of vint.end() once outside the body
>of the loop, and use that constant value for the terminal point of the loop.
>(though, physician 'heal thyself' would be appropriate here, since I always
>turn to the less efficient manner in my own code -- since my fingers almost
>automatically key the code in :) .
>
>5. (p. 7) prefer '\n' to endl. On some systems, the overhead of calling
>endl can be significant. In addition, in web applications, where probably
>75% of the code involves writing output to the web browser, using '\n' can
>dramatically improve response times.
>
>
Yes, I am guilty of ignoring these points on purpose. It was late and
they have been mentioned, I thought, in other writings by Herb. Probably
my biggest excuse that it was late.
Also, I am personally guilty of violating both. But for what I do, it
probably does not matter. I am also always under the gun and it is
easier to type endl to '\n" and it != vint.end() to storing end()
somewhere. My vectors are usually small and I don't see problems in my
profiler.
I understand everyone's concern for for_each(), I use for_each to call
member functions of the elements and use boost mem_func and bind since I
think they are clearer. I am the only one who reads my code currently
even though I am trying to change that. We will see how well STL and
for_each is understood when I need to teach others. :-) . I have not
used boost::lambda yet but have thought about it.
If the functor is small and can be written near the for_each call, I
think for_each is easier to read and type then hand coding the loop.
But if I needed to store the functors somewhere else for sharing, I can
see the problems. I have had second thoughts on the code because all
these functors scattered all over.
More information about the Effective-cpp
mailing list