views:

265

answers:

5
+2  Q: 

Register Variables

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

+5  A: 

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.

anon
+1  A: 

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.

Mykola Golubyev
This will not enhance performance but it will clearly reduce stack overflow problems.
David Rodríguez - dribeas
A: 

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.

Lazarus
A: 

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.

unwind
Is there way to find out if the compiler has embraced the request for register variables ?
sameer karjatkar
@sameer: analyze the the assembly, but that is not a trivial task if the methods are complex
David Rodríguez - dribeas
+7  A: 

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.

David Rodríguez - dribeas