2

I have an application that makes extensive use of STL vectors and Boost multiarrays. The application is very sensitive to performance since it profiles large amounts of data in real time.

Since vectors and multiarrays do out of bounds checks, I would expect to incur some performance penalty as a result. I was wondering if there was a way to allow error checking only during development, but disable it in production.

So, I would like to know if this is indeed possible, and whether it would make a difference to the performance of my containers?

Gumbly jr.
  • 729
  • 2
  • 9
  • 18

2 Answers2

2

In practice, all STL implementations that I've looked at (VC, GCC, etc.) do exactly what you want. They might have some bounds checking in debug/development builds, but they omit them all when you are building for release. This is true (AFAIK) for Boost containers too (e.g. see here, as mentioned in another answer.)

In some cases, different access methods have different behaviors in terms of bounds checking. For example, the std::vector member function at() always does perform bounds checks, but the indexing operator ([]) doesn't do so in release/nondebug builds.

In the end, if it is this important to you, you should just look at the implementation you are using and make sure. It's just a handful of functions on a few containers.

About the performance cost of bounds checking. In practice, all the provided STL algorithms will use unchecked access into the containers (they do their error checking up front and from then on won't bother.) Therefore, if you use STL algorithms, you won't see any performance overhead whatsoever.

In your own code, inside your tight inner loops, you might see a negative impact on performance from bound checks. I haven't done any benchmarks but I imagine it would be minimal and negligible in most cases. Also, in the vast majority of use cases, you can replace your hand-written loops with STL algorithms (for_each, accumulate, count_if, etc.) which will eliminate even that minimal cost.

yzt
  • 8,873
  • 1
  • 35
  • 44
2

In boost, the answer to your question is here: http://lists.boost.org/boost-users/2006/02/16960.php

In short, The range checks are based on boost/assert.hpp: they can be disabled by either defining BOOST_DISABLE_ASSERTS or NDEBUG (you can pass one of these as a compiler option).

In std vectors, at() does bounds checking, but [] does not. In most common compiler implementations, it is possible to enable bounds checking, but this has to be done explicitly (typically by passing a special flag, or enabling debug mode). So your [] operations are already optimized for vectors.

CinCout
  • 9,486
  • 12
  • 49
  • 67
Spacemoose
  • 3,856
  • 1
  • 27
  • 48