This section of the archives stores flipcode's complete Developer Toolbox collection, featuring a variety of mini-articles and source code contributions from our readers.

 

  Why Prefix Is Better Than Postfix With STL
  Submitted by



I've noticed that a lot of people arbitrarily use postfix operators out of habit when working with operations where execution order is not important. For example, lots of people do this:

for(int count = 0; count < 10; count++)
{
} 



This is fine when the variable are basic types, but I think this is a good habit to get out of when you use STL. Take the example of these two iterator loops:

std::list<Object aList;

for(std::list<Object::iterator iter = aList.begin(); iter != aList.end(); iter++) { }

for(std::list<Object::iterator iter = aList.begin(); iter != aList.end(); ++iter) { }



A subtle difference, but a big one. Let's see how the pre and postfix operators are defined in the Microsoft implementation since lots of folks probably use this by default, and it's fairly representative of how many implementations work. The first function is the postfix operator and the later is the prefix operator.

iterator operator++(int)
{
	iterator _Tmp = *this;
	++*this;
	return (_Tmp);
}

iterator& operator++() { _Ptr = _Acc::_Next(_Ptr); return (*this); }



See the performance hit? Because postfix operations must occur after any operations, it must make a copy of the object it's operation on first to preserve the original state of the object. This means the copy constructor gets invoked on the object, and this can be very expensive if something like a string copy is involved, and is generally a waste of valuable instructions. For that matter, it winds up calling the prefix operator anyway! The prefix operator doesn't have to worry about the data changing, so it's free to do what it wants, which is to just set the iterator to point to the next object in the list.

So the moral of the story is, "Unless you absolutely need to use postfix, get in the habit of using prefix."

-Chris Blackwell


The zip file viewer built into the Developer Toolbox made use of the zlib library, as well as the zlibdll source additions.

 

Copyright 1999-2008 (C) FLIPCODE.COM and/or the original content author(s). All rights reserved.
Please read our Terms, Conditions, and Privacy information.