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
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
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.
You can change you algorithm to just use std::stack
and some custom class which will contain state of the algorithm instead of function stack and recursion call.
If I remember correctly the register keyword doesn't guarantee the variable will get stored in a register but indicates that it could and if possible should use a register however, if a register isn't available then it's still going to end up on the stack.
Microsoft C++ ignores the keyword and makes it's own decisions. I'd look to your algorithm first for performance gains.
It is 100% up to the compiler to honor your register
request. Sure, you might conserve stack space if you manage to squeeze a local variable or two into registers, but not (of course) if those values need to be preserved across calls as then they will need to be put on the stack again.
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.