How to write Inline Functions in Python?

Delaney, Timothy tdelaney at avaya.com
Thu Nov 14 19:13:50 EST 2002


[python code with timings ommitted]

The above is a completely different situation - it is a case of inlining
code directly.

An 'inline function' in C++ is declared with the 'inline' keyword, and
(normally) is placed in the header file. It is also normally a class method
(although doesn't have to be).

It is simply a *hint* to the compiler that the programmer thinks this
function should be inlined. It can be ignored.

The major problem with 'inline' is that it mixes up the code with the
declarations. Whilst this is not an issue in Python (since there are no
separate declarations) it tends to cause an unholy mess in C++ header files
- instead of being able to say "the interface is defined in the .h file, and
the implementation is in the .cpp file" you now have a mix of "the interface
and some of the implementation is in the .h file, and the rest of the
implementation is in the .cpp file". This causes a mess, breaks
encapsulation, etc ...

For some things in C++, inlining is required (in particular, some things to
do with templates). IMO it's not worth the mess to use those features -
avoid them and keep the interface and implementation completely separate in
C++.

In real-world performance, using the 'inline' hint in C++ is usually
worthless. If you have an optimising compiler, it will tend to ignore your
hint, and determine for itself what should be inlined (and it's usually a
better guesser than you are). If you *don't* have an optimising compiler,
then usually one of two things will occur: the compiler will blindly obey
all your 'inline' hints, usually leading to code bloat and optimisation of
things that don't need to be, or will blindly ignore all your 'inline' hints
and will inline nothing.

I've seen lots of code which 'inline'd things all over the place ... and
then used the STL in performance-critical sections.

It comes down to the two rules of optimisation (Knuth? Jackson?):

1. Don't do it.
2. (For experts only) Don't do it yet.

Tim Delaney




More information about the Python-list mailing list