BOOST_FOREACH
and c++11 range based loop? BOOST_FOREACH
instead of range based loop or vice versa?After executing a little test with std::vector
filled with 1,000,000 int
variables I found out that BOOST_FOREACH
is a little bit slower than range based loop (took about 1.25 times longer than for a ranged based loop).
The main difference is that range-for is a language construct, while BOOST_FOREACH
is a macro doing lots of magic under the hood to do something that looks like that language construct. It is trying to do exactly the same thing with the limitations of pre-C++11. The goal of BOOST_FOREACH
is range-for.
There is exactly one situation where I would even think of using BOOST_FOREACH
instead of range-for, and it is iterating over a container of tuples where you want to unroll the tuple:
std::map<int, int> m;
int key, value;
BOOST_FOREACH(boost::tie(key, value), m)
{
// do something with key and value here
}
as compared to:
int key, value;
for (const auto& pair : m)
{
std::tie(key, value) = pair;
// do something
}
I like that you can put the tie
directly into the loop header, although ultimately that's such a minor advantage that it's hardly worth even considering this as being a decision. Use range-for. Always.
C++17 will introduce structured bindings, which remove even that minor syntactical advantage:
for (auto const& [key, value] : m)
{
// do something
}
At that point, there will be no reason whatsoever to use BOOST_FOREACH
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With