Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register Variables

Tags:

c++

recursion

I am having a C++ code which have lot of recursion involved . I am thinking of using register class for my variables . Do you think by doing so I will be saving stack memory and will improve the performance

Thanks

Sameer

like image 809
sameer karjatkar Avatar asked Jul 13 '26 15:07

sameer karjatkar


2 Answers

I could bet that the compiler is NOT going to honor your request. Say that you have a local variable, and that you recursively call the function 100 times. If it were to honor all your auto variables 'register' keyword it would require 100 hardware registers just for that variable (all the variables are alive at the 100th call)

Performance is a difficult problem. Analyze where is the program really spending time and try to optimize there, but be cautious: some decisions can end in no gain, some can end up in worse performance. As it has been mentioned before, compilers are really good at what they do. Forcing a variable into a register means one less register for the rest of the variables to use.

like image 159
David Rodríguez - dribeas Avatar answered Jul 16 '26 06:07

David Rodríguez - dribeas


No, I think it will probably have no effect at all. Modern compilers are typically much better at scheduling register use than humans, and will probably ignore the "register" keyword.

Having said that, the only real way to find out is to write some code and measure its performance with the register keyword and without it - the code change is trivial.