Compiler optimizations

26 Oct 2005

I just stumbled upon the article Dynamic compilation and performance measurement, which is about how difficult it is to measure performance using short test programs (microbenchmarks). The article is about how dynamic languages such as Java makes performance measurement even harder than for static languages such as C++, but the point with dead code elimination is valid for static languages too.

For example, consider the following C++ code:

int example1() {
  return 10000;
int example2() {
  return 5000 + 5000;
int example3() {
  int i = 0;
  while(i < 10000) {
  return i;

All of these obviously returns 10000, but how is the performance? Many programmers would assume that example1 is the fastest, and fail to realize that any modern compiler, when compiling with optimization, will generate the very same, or equivalent, code for all of the above functions. And it doesn't stop there. Compilers today can often do surprisingly clever optimizations, so don't listen to optimization advice based on 10 year old compilers. The way to be sure if there is a difference is to look at the generated machine code, or benchmarking in a real world application.

blog comments powered by Disqus