c++compiler-optimization

Compiler optimization Duplicate Classes


I am using C++ as intermediate language, for each function object I am creating a unique class with a call method. What I am avoiding is checking if a similar function is already used and its corresponding class defined, so I may end up with exact same class with a different name. So I am wondering if compiler (g++) will detect this and merge classes.


Solution

  • Just to clarify on both previous answers (which are good answers):

    The compiler will absolutely not merge your classes, at all. Some linkers might have some optimizations along those lines, but it's by no means a standard feature and neither the standard Microsoft nor GNU/Linux linkers do that. Usually the linker will only do that if you emit weak entries with the same name in the object files directly, which is what happens with template instantiations for instance. There is no standard way to obtain this behavior in C/C++ directly, although at least GCC offers extensions to control this linking yourself.

    You should do it yourself though because it actually is an optimization. Jason is right that it would "just" cut down on code size, but on modern PC architectures that is itself a huge optimization. The code caches on the CPU aren't getting much bigger and memory speeds are nowhere close to CPU speeds, so cache misses caused by having an overly huge code image can have very serious performance impacts. There are benchmarks showing that compiling the Linux kernel or large apps like Firefox or OpenOffice with -Os (optimize for size) is faster in some workloads by a wide margin than when compiled with -O3.