Item 5: Prefer range member functions to their single-element counterparts

 1. It's generally less work to write the code using the range member functions.  Or  you'd  have  to  write  an  explicit  loop, and  the loop also happens to impose an efficiency penalty.
 2. Range  member  functions  tend  to  lead  to  code  that  is  clearer  and  more straightforward.
 3.Almost all uses of copy where the destination range is specified using an insert iterator should be replaced with calls to range member functions, because the copy alogrithm is actually using a single-element member functions.
 4. When  dealing  with  the standard sequence containers, application of single-element member functions makes more demands on memory allocators, copies objects more frequently, and/or performs redundant operations compared to range member functions that achieve the same end.
 The following analysis applies for vector, string, and deque
    a.The first tax consists of unnecessary function calls.
    b.the second tax, which is the cost of inefficiently moving the  existing  elements  in  v  to  their  final  post-insertion  positions.In contrast, the Standard requires that range insert functions move existing container elements directly into their final positions.
    c.The final performance tax levied on those so foolish as to use repeated single-element insertions instead of a single range insertion has to do with memory allocation, though it has a nasty copying side to it, too

 As to list, first item marked as 'a' still stands, and a new problem for single-element member functions is repeated  superfluous  assignments  to  the  next and prev pointers of some nodes in the list.

 For the associative containers, the efficiency case is harder to make, though the issue of extra function  call  overhead  for  repeated  calls  to  single-element  insert  continues  to  apply. Furthermore,  certain  special  kinds  of  range  insertions  may  lead  to  optimization possibilities in associative containers, too, but as far as I can tell, such optimizations currently exist only in theory. By the time you read this, of course, theory may have become practice, so range insertions into associative containers may indeed be more efficient  than  repeated  single-element  insertions.  Certainly  they  are  never  less efficient, so you have nothing to lose by preferring them.
posted @ 2009-08-23 22:49  Aldrich  阅读(381)  评论(0)    收藏  举报