optimization of boost::end

The common idiom is: for (; i != boost::end (vector); ++i) ... The compiler had damn well better realize that boost::end is a constant function that can be lifted from the loop, or performance can be severely impacted. Does anyone have any experience with this? Is there a portable way to give hints to the compiler? Should boost provide such a facility?

I don't think this is optimized by any C++ compiler. The body of the for-loop might modify the sequence and invalidate the end() iterator of the previous iteration. Therefore I don't think it's possible for the compiler or boost to optimize this. You could write: for (Iterator i = boost::begin(x), last = boost::end(x); i != last; ++i) ... for_each(boost::begin(x), boost::end(x), ... ) Or use boost::range_ex (see range_ex.zip in the root of boost vault) to use: for_each(x, ... ) Or use the BOOST_FOR_EACH macro. The intent to not modify the iterator needs to be more explicitly stated to allow the optimization while ensuring correctness. HTH, Neil Groves On Jan 3, 2008 2:42 PM, Neal Becker <ndbecker2@gmail.com> wrote:
The common idiom is:
for (; i != boost::end (vector); ++i) ...
The compiler had damn well better realize that boost::end is a constant function that can be lifted from the loop, or performance can be severely impacted.
Does anyone have any experience with this? Is there a portable way to give hints to the compiler? Should boost provide such a facility?
_______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost

Neal Becker wrote:
The common idiom is:
for (; i != boost::end (vector); ++i) ...
The compiler had damn well better realize that boost::end is a constant function that can be lifted from the loop, or performance can be severely impacted.
boost::end is not a constant function, because the vector can change. However, boost::end(vector) is the same as vector._M_begin + vector._M_size (implementation specific names) I wouldn't say one addition can severely impact performance. I believe a lot of optimizers can optimize out that addition if the vector wasn't changed anyway.

Mathias Gaunard wrote:
Neal Becker wrote:
The common idiom is:
for (; i != boost::end (vector); ++i) ...
The compiler had damn well better realize that boost::end is a constant function that can be lifted from the loop, or performance can be severely impacted.
boost::end is not a constant function, because the vector can change.
However, boost::end(vector) is the same as vector._M_begin + vector._M_size (implementation specific names) I wouldn't say one addition can severely impact performance.
I believe a lot of optimizers can optimize out that addition if the vector wasn't changed anyway.
Sorry I was not clear. I did not mean std::vector, I meant a generic vector concept.
participants (3)
-
Mathias Gaunard
-
Neal Becker
-
Neil Groves