www.delorie.com/djgpp/doc/ug/compiling/inline-f.html | search |
This chapter discusses inline functions. These are the various topics that will be covered in the chapter:
Inline functions are the best way to shortcut time criticle calls in any program from video games to accounting. They offer the best results for the least amount of work, compared to other forms I'll discuss later. Hold on to your hat because its faster than you think! Inline functions only require one extra comment. The inline comment is a request to the compiler to copy the code into the object in order to make a "short jump" instead of a "long jump." This request does not always occur due to certain limitations.
/* FOO.C */ int foo(int a, int b) { return (a-b) + (a * b); } /* INLINE VERSION: FOO.C */ inline int foo(int a, int b) { return (a-b) + (a * b); }
Ok here is the big question that everyone wants to know. What is faster, functions, inlined functions, or macros? Well common sense will knock off the first option, functions. The truth is inlined functions are not the fastest form of coding but they are the best way to go if don't have a few years to debug a project written with macros.
/* MACRO VERSION: FOO.H */ #define foo(a, b) \ { \ return (a-b) + (a * b); \ }
The problem with macros is that the code is literally copied into the location it was called from. So if the user passes a "double" instead of an "int" then problems could occur. However, if this senerio happens with an inline function the compiler will complain about incompatible types. This will save you hours in the debug stage, trust me! The honest truth is that macros are but a fraction of nano seconds faster, so the cost does not outweigh the benefits by any stretch of the imaginination. After optimizations, (refer to "speeding up your program"), you'll have a regular speed demon on your hands.
The best time to use inline functions is when:
Avoid inlining rediculously large functions unless absolutely nececary. Try to keep them as simple as possible, inline functions could really blow up your cache if taken lightly.
Note to C++ programmers: When declaring and defining a function within a class, the function is automatically inlined so there is no need for the extra inline request.
// FOO.HH in C++ class foo { pritvate: int a, b; public: inline int get_a(); // defined else where, inline is needed int get_b() { return b; }// don't bother!! };
webmaster donations bookstore | delorie software privacy |
Copyright © 1998 by DJ Delorie | Updated Oct 1998 |
You can help support this site by visiting the advertisers that sponsor it! (only once each, though)