How to use functions more efficiently

From ArticleWorld


Functions (also known as methods) are one of the fundamental building blocks of programs. They allow you to abstract your code, making it easier to read, maintain and re-use.

However, function calling is also adding some CPU overhead. This guide attempts to explain some steps to take in order to make a compromise between code readability and performance.

Procedure

It is important to optimize your functions while writing them. Some post-optimization can obviously be done after you have finished coding, but do as much optimization as you can in the process.

1. Use functions only for the most general pieces of code. Functions are a generalization, just like their mathematical counterparts. If an action will only be performed once, on a single set of objects, you should just write the code by itself. Or, see #2.

2. Learn to use inline functions. Inline functions (preceded by the inline operator on most compilers) are turned into code that is literally part of the program's body.

When you are calling a function, the computer suspends the execution of the function in progress (the main function at least) and executes a piece of code stored somewhere else. If the function is inline, the code is simply put in the body of the function in progress, saving a system call.

Inline functions are either very short functions that get called many times, or functions that are only performed once on a limited set of objects. The later is only for code readability, but it helps.

3. Static functions are faster to call. However, not functions can be declared as static. Learn how to use static functions (those that are always stored at the same address). They are powerful, but tricky to debug at times.

4. Avoid iterative function calls when possible. For example, if you know that a function will be applied to a range of objects, why not re-write the function to take the range as argument and perform the iteration itself? If there are only two or three known cases, you can safely overload it, too, in languages that support it.

5. When passing parameters larger than 4 bytes (8 bytes on 64-bit CPUs), use reference passing and return value. References take less space.