How to optimize variable usage in C/C

From ArticleWorld


It may seem amazing how even something like variables can be optimized. But still, this is true. Some things about how you use variables can be changed for better performance of readability.

The steps outlined below should be carried out during the actual coding phase as much as possible. Some optimization can be carried on later, but it may not be so easy.

Steps

1. Refrain from using local variables unless absolutely necessary. Most compilers are able to fit these into registers (see #2 as well) and work easier with them. When using no local variables at all, there will be no need to set up and restore a frame pointer.

This is not to say that you should not use local variables. Just use them wisely.

2. The register keyword supported by some compilers will force the compiler to store a variable in a register. Used carefully (i.e. not in excess), this can seriously improve the performance.

3. When using local variables, declare them in the innermost scope/block code. Consider the following example:

int DoSomething(int number) {
if (number == SOME_VALUE) {
        switch (someFunctionCall()) {
	....
	case ANOTHER_VALUE:
		SomeCustomType var;
		...
        ...
        }
    }
}

In C++, most compilers will try to allocate local variables as they encounter them, and this takes some overhead. In the example above, the default constructor for var will only be called if the ANOTHER_VALUE case occurs.

4. When you do not need literal values, use int instead of char and short. You can use these even if you really manipulate character arrays in the meaning of literal strings (not just 8-bit values), but this may break some functions.

The inner pointer arithmetics of C/C++ compilers uses int more efficiently.