C++ tricks, #2: Parameter passing

This post is very old. Please bear in mind that information here might be incorrect or obsolete, and links can be broken. If something seems wrong, please feel free to comment or contact me and I'll update the post.

From time to time, I’m taking a look at Aqsis, and recently I started a discussion about passing parameters by const reference instead of value for integral types, under the assumption that it is just as fast (as the compiler notices hey this type fits in a register, don’t bother passing a pointer …). I was quite sure I have seen this with VC7.1. However, Chris Foster wrote a small test case that showed there is indeed a difference, from 1-2% with VC8 (and the generated ASM is different) to 5% (GCC4) to 100% (GCC 3.4) So, passing floats by const reference is no good if you want fast code (except you’re using Intel C++, this one did optimize it).

If you are writing generic code, where you don’t know how large your types are, there is a Boost.org provided solution that I totally forgot (thanks Andrew J. Bromage for pointing it out) that selects the optimal type for parameter passing depending on whether the type is smaller than a pointer or not: Call traits, which work great and do their job.

Related posts:

  1. C++ tricks, #1: Compile time checks
  2. C++ tricks, #4: Binding to overloaded member functions
  3. C++ tricks, #6: Explicit template instantiation

This entry was posted in Programming and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>