Code Tips and Snippets


Not yet member?
Click here to register.
Only members can post comments
Optimizing your C/C++ code by using register!
Posted by pk on Saturday, November 07 2015 - 15:48:25
2 stars levelC Language

Monday april 06, 2020 Update: Obsolete article
Last tests had been done on ubuntu 12.04...
gcc Optimizer doesn't need anymore register
What has been true during 30 years is now no more true!


During the seventies, at the very beginning of the C language, the register keyword has been introduced in order to allow the programmer to give hints to the compiler, telling it that the variable would be used very often, and that it should be wise to keep it’s value in one of the processor’s internal register.

Nowadays, optimizers are much more efficient than programmers to determine  variables  that are more likely to be kept into registers, and the optimizer does not always take the programmer’s hint into account.

So many people wrongly recommend not to use the register keyword.

Let’s see why!

The register keyword has an associated side effect: you can not reference (get the address of) a register type variable.

People advising others not to use registers takes wrongly this as an additional argument.

However, the simple fact of knowing that you can not take the address of a register variable, allows the compiler (and its optimizer) to know that the value of this variable can not be modified indirectly through a pointer.

When at a certain point of the instruction stream, a register variable has its value assigned in a processor’s register, and the register has not been used since to get the value of another variable, the compiler knows that it does not need to re-load the value of the variable in that register.
This allows to avoid expensive useless memory access.

Do your own tests and you will get significant performance improvements in your most inner loops.

yakpro rulez!

Site has been updated on Wednesday, January 19 2022 - 09:43:57